\global\long\def\gunderline#1{\mathunderline{greenunder}{#1}}%
\global\long\def\bef{\forwardcompose}%
\global\long\def\bbnum#1{\custombb{#1}}%
\global\long\def\pplus{{\displaystyle }{+\negmedspace+}}%


\chapter{Computations in functor blocks. III. Monad transformers\label{chap:monad-transformers}}

\section{Practical use}

\subsection{Combining monadic effects via functor composition}

Monads describe effects that depend on previously computed values.
It is often necessary to combine effects of several monads in one.
For example, the effect of \lstinline!Future! is to compute values
concurrently, while \lstinline!Option! represents a possibly missing
value. To describe a possibly missing value that is computed concurrently,
we need somehow to combine \lstinline!Future! with \lstinline!Option!.

The type constructors \lstinline!Future! and \lstinline!Option!
are not equivalent, so we cannot simply use them together in one functor
block:
\begin{lstlisting}
for {
  x <- Future(1)
  y <- Option(x + 1) // Type error.
  ...
\end{lstlisting}

One way of combining two effects is by using functor composition,
\lstinline!Future[Option[A]]!. However, we run into a problem if
we want to use a result value within the nested type. For instance,
this code will not compile:
\begin{lstlisting}
for {
  xOpt <- Future(Option(1))       // xOpt: Option[Int]
  x    <- xOpt    // We would like to get x: Int here.
  ...
\end{lstlisting}
The source types must be compatible throughout the entire functor
block; we cannot mix source lines of \lstinline!Future! and \lstinline!Option!
types. We could work with the nested data type using code like this:
\begin{lstlisting}
val result: Future[Option[Int]] = for {
  xOpt <- Future(Option(1))  // xOpt: Option[Int]
  tOpt <- xOpt match {       // yOpt: Option[Int]
    case None     => Future.successful(None)     // This expression must be a Future[Option[Int]].
    case Some(x)  => for {
        yOpt <- Future(Option(x + 1))
        zOpt <- yOpt match { // zOpt: Option[Int]
          case None    => Future.successful(None) // Must return a Future[Option[Int]] everywhere.
          case Some(y) => Future(Option(y + 3))
        }
      } yield zOpt
  }
} yield tOpt
\end{lstlisting}
The nested type constructor forces us to use pattern matching with
nested functor blocks, since that is the only way of getting access
to values of type \lstinline!A! within \lstinline!Future[Option[A]]!.
The code is repetitive and deeply nested, which makes it hard to read
and to change. 

The first step towards solving the problem is to rewrite this monadic
program as a direct chain of computations depending on the results
of previous ones:
\begin{lstlisting}
val result: Future[Option[Int]] = for { // This will not compile!
  x <- Future(Option(1))                // The type is x: Option[Int], although we wanted x: Int.
  y <- Future(Option(x + 1))            // Type error: x + 1 is undefined.
  z <- Future(Option(y + 3))
} yield z
\end{lstlisting}
To be able to write code in this way, we need to implement the \lstinline!flatMap!
operation directly on the type \lstinline!Future[Option[A]]! with
respect to the type parameter \lstinline!A!. Let us wrap the type
\lstinline!Future[Option[A]]! into a class and implement the \lstinline!map!
and \lstinline!flatMap! methods:
\begin{lstlisting}
final case class FutOpt[A](nested: Future[Option[A]]) {
  def map[B](f: A => B)(implicit ec: ExecutionContext): FutOpt[B] = FutOpt(nested.map(_.map(f)))
  def flatMap[B](f: A => FutOpt[B])(implicit ec: ExecutionContext): FutOpt[B] =
    FutOpt(nested.flatMap {      // Provide a function Option[A] => Future[Option[B]].
      case None    => Future.successful(None) // Must return a Future[Option[B]] here.
      case Some(x) => f(x).nested
    })
}

import scala.concurrent.ExecutionContext.Implicits.global
val result: FutOpt[Int] = for {      // This code compiles now.
  x <- FutOpt(Future(Option(1)))     // x: Int
  y <- FutOpt(Future(Option(x + 1))) // y: Int
  z <- FutOpt(Future(Option(y + 3))) // z: Int
} yield z
\end{lstlisting}
To shorten the code, we define conversions (\textsf{``}lifts\textsf{''}) from \lstinline!Future!
to \lstinline!FutOpt! and from \lstinline!Option! to \lstinline!FutOpt!:
\begin{lstlisting}
implicit class FutOptLift1[A](fut: Future[A])(implicit ec: ExecutionContext) {
  def up: FutOpt[A] = FutOpt(fut.map(x => Some(x)))
}
implicit class FutOptLift2[A](opt: Option[A]) {
  def up: FutOpt[A] = FutOpt(Future.successful(opt))
}
\end{lstlisting}
We can now rewrite the previous code in a more readable form:
\begin{lstlisting}
val result: FutOpt[Int] = for {
  x <- Option(1).up     // x: Int
  y <- Future(x + 1).up // y: Int
  z <- Option(y + 3).up // z: Int
} yield z  // This eventually evaluates to `FutOpt(Future.Successful(Some(5)))`.
\end{lstlisting}

We may hope to apply the same technique when mixing effects from arbitrary
monads, such as:
\begin{lstlisting}
val result: SomeBigMonad[Int] = for {  // After some definitions, this code should work:
  x <- (1 to n).up                     // x: Int
  y <- Future { computation(x) }.up    // y: Int
  z <- Try { maybeError(y) }.up        // z: Int
} yield z
\end{lstlisting}
This code will work if we somehow create a new monad that combines
\lstinline!Seq!, \lstinline!Future!, and \lstinline!Try!. 

It turns out that there is no simple recipe for implementing a combined
monad out of a given set of monads. Developing the necessary techniques
is the focus of this chapter.

We have seen that \lstinline!Future[A]! and \lstinline!Option[A]!
are combined in a new monad as \lstinline!Future[Option[A]]!. Does
functor composition always work? If $M_{1}$ and $M_{2}$ are monads
then at least one of the compositions, $M_{1}\circ M_{2}$ or $M_{2}\circ M_{1}$,
is sometimes a monad. However, \lstinline!Option[Future[A]]! is not
a monad. By trial and error, we may find further examples where the
functor composition works and where it does not (see Table~\ref{tab:Correct-and-incorrect-compositions};
incorrect choices are marked with a strike-through line).

It turns out that some monads do not compose in either order, while
others have a \textsf{``}preferred\textsf{''} order (we will see proofs of these properties
later in this chapter). For instance, the \lstinline!Reader! monad
($M^{A}\triangleq R\rightarrow A$) always composes on the outside
(Statement~\ref{subsec:Statement-monad-construction-1}) but not
necessarily on the inside. On the other hand, the \lstinline!Either!
monad ($M^{A}\triangleq Z+A$) always composes on the inside (we will
prove that in Section~\ref{sec:transformers-linear-monads}), but
not necessarily on the outside.

\subsubsection{Example \label{subsec:Example-either-reader-not-compose}\ref{subsec:Example-either-reader-not-compose}\index{solved examples}}

Show that a \lstinline!Reader! monad does not compose inside of an
\lstinline!Either! monad.

\subparagraph{Solution}

The \lstinline!flatMap! method\textsf{'}s type signature cannot be implemented
for the type constructor $F^{A}\triangleq Z+\left(R\rightarrow A\right)$,
where $R$ and $Z$ are fixed (but otherwise unknown) types. Begin
writing the code:
\begin{lstlisting}[numbers=left]
def flatMap[A, B](fa: Either[Z, R => A])(f: A => Either[Z, R => B]): Either[Z, R => B] = fa match {
  case Left(z)    => Left(z)     // No other choice here.
  case Right(h)   => Right(r =>  // Cannot return a Left() here, since we have no values of type Z.
      val x: Either[Z, R => B] = f(ra(r))     // Can compute a value `x` of type Either[Z, R => B].
      ???                 )      // Need to return a value of type B here, using only r, ra, and f.
}
\end{lstlisting}
In line~3, we must decide whether to return a \lstinline!Left(...)!
or a \lstinline!Right(...)!, given only values $h^{:R\rightarrow A}$
and $f^{:A\rightarrow Z+\left(R\rightarrow B\right)}$. The decision
must be hard-coded since at that point we have no values of type $R$
or $A$, so we cannot apply the functions $f$ and $h$ to any arguments.
The only possible decision is to return a \lstinline!Right(...)!.
But then we are not able to compute a value of type $B$ in the scope
of lines~3\textendash 5 because we cannot guarantee that the value
$x^{:Z+\left(R\rightarrow B\right)}$ contains a function $R\rightarrow B$
rather than a value of type $Z$. So, the typed hole $\text{???}^{:B}$
in line~5 cannot be filled. $\square$

When the monad composition works both ways, the two resulting monads
are usually not equivalent: the effects combined in different order
behave differently. For example, the \lstinline!Writer! monad $W\times A$
(\textsf{``}appending a log message\textsf{''}) and the \lstinline!Either! monad
$Z+A$ (allowing failure) can be composed in two ways. The monad $M^{A}\triangleq W\times\left(Z+A\right)$
describes a computation that may fail but always appends a message.
The monad $M^{A}\triangleq Z+W\times A$ will not append any message
on failure.
\begin{center}
\begin{table}[h]
\begin{centering}
\vspace{-0.8\baselineskip}
\begin{tabular}{|c|c|c|c|}
\hline 
\textbf{\small{}Monad $M_{1}^{A}$} & \textbf{\small{}Monad $M_{2}^{A}$} & \textbf{\small{}$M_{1}\circ M_{2}$} & \textbf{\small{}$M_{2}\circ M_{1}$}\tabularnewline
\hline 
\hline 
{\small{}$\text{Future}^{A}$} & {\small{}$Z+A$} & {\small{}$\text{Future}^{Z+A}$} & {\small{}\sout{\mbox{$Z+\text{Future}^{A}$}}}\tabularnewline
\hline 
\texttt{\small{}Future{[}A{]}} & \texttt{\small{}State{[}S, A{]}} & \texttt{\small{}\sout{Future{[}State{[}S, A{]}{]}}} & \texttt{\small{}\sout{State{[}S, Future{[}A{]}{]}}}\tabularnewline
\hline 
\texttt{\small{}State{[}S, A{]}} & {\small{}$Z\rightarrow A$} & \texttt{\small{}\sout{State{[}S, Z => A{]}}} & \texttt{\small{}Z => State{[}S, A{]}}\tabularnewline
\hline 
\texttt{\small{}State{[}S, A{]}} & {\small{}$Z+A$} & \texttt{\small{}State{[}S, Either{[}Z, A{]}{]}} & \texttt{\small{}\sout{Either{[}Z, State{[}S, A{]}{]}}}\tabularnewline
\hline 
{\small{}$\text{List}^{A}$} & {\small{}$Z\rightarrow A$} & {\small{}\sout{\mbox{$\text{List}^{Z\rightarrow A}$}}} & {\small{}$Z\rightarrow\text{List}^{A}$}\tabularnewline
\hline 
{\small{}$\text{List}^{A}$} & {\small{}$Z+A$} & {\small{}$\text{List}^{Z+A}$} & {\small{}\sout{\mbox{$Z+\text{List}^{A}$}}}\tabularnewline
\hline 
{\small{}$\bbnum 1+A$} & {\small{}$Z\rightarrow A$} & {\small{}\sout{\mbox{$\bbnum 1+\left(Z\rightarrow A\right)$}}} & {\small{}$Z\rightarrow\bbnum 1+A$}\tabularnewline
\hline 
{\small{}$W\times A$} & {\small{}$Z+A$} & {\small{}$W\times\left(Z+A\right)$} & {\small{}$Z+W\times A$}\tabularnewline
\hline 
\end{tabular}
\par\end{centering}
\caption{\label{tab:Correct-and-incorrect-compositions}Correct and incorrect
compositions of monads.}
\vspace{-2\baselineskip}
\end{table}
\par\end{center}

Throughout this chapter, we will see other examples of monads whose
effects can be combined in different order. The programmer needs to
choose carefully the order of composition, according to the desired
behavior of the effects.

When functor composition works, implementing the \lstinline!up! methods
is straightforward:

\subsubsection{Example \label{subsec:Example-lift-for-List-Try-composition}\ref{subsec:Example-lift-for-List-Try-composition}}

Implement a composition of \lstinline!List! and \lstinline!Try!
monads for use in functor blocks.

\subparagraph{Solution}

Since \lstinline!Try! is a pass/fail monad, we must compose it \emph{inside}
other monads. So, we define the combined monad type as \lstinline!List[Try[A]]!.
We wrap the type \lstinline!List[Try[A]]! into a class, implement
\lstinline!map! and \lstinline!flatMap! as methods, and then define
the two \lstinline!up! functions (the \textsf{``}lifts\textsf{''}) as extension methods:
\begin{lstlisting}
final case class ListTry[A](value: List[Try[A]]) {
  def map[B](f: A => B): ListTry[B] = ListTry(value.map(_.map(f)))
  def flatMap[B](f: A => ListTry[B]): ListTry[B] = ListTry(
    value.flatMap {        // Need to provide a function Try[A] => List[Try[B]] here.
      case Failure(t)   => List(Failure(t))
      case Success(a)   => f(a).value
    })
}
def pure[A](a: A): ListTry[A] = ListTry(List(Success(a)))
implicit class ListTryLift1[A](l: List[A]) { def up: ListTry[A] = ListTry(l.map(Success(_))) }
implicit class ListTryLift2[A](t: Try[A]) { def up: ListTry[A] = ListTry(List(t)) }
\end{lstlisting}
After these definitions, we can write functor blocks that use \lstinline!List!
and/or \lstinline!Try! as needed:
\begin{lstlisting}
scala> for {
         x <- List(1, 2, 3).up
         y <- Try(x + 100).up
       } yield y
res0: ListTry[Int] = ListTry(List(Success(101), Success(102), Success(103)))
\end{lstlisting}

The following examples show that the functor composition does not
always work. For instance, the \lstinline!State! monad does not always
compose with other monads in either order.

\subsubsection{Example \label{subsec:Example-state-monad-composition-fails-with-option}\ref{subsec:Example-state-monad-composition-fails-with-option}}

Show that the \lstinline!State! monad fails to compose inside the
\lstinline!Option! monad.

\subparagraph{Solution}

There is no lawful \lstinline!flatMap! function for the type constructor
\lstinline!Option[State[S, A]]!:
\begin{lstlisting}
type OpSt[A] = Option[S => (A, S)]                 // Here, the fixed type S must be already defined.
def flatMap[A, B](fa: OpSt[A])(f: A => OpSt[B]): OpSt[B] = fa match {
  case None      => None         // No other choice here.
  case Some(sta) => Some( s =>   // If we return `None` here, we will violate the monad identity law.
         // We need to return a value of type (S, B) in this scope, using given values f, sta, and s.
    val (s1, a) = sta(s) // We can compute another value of type s. But can we get a value of type B?
    val b: B = f(a) match {     // The only way of possibly getting `b: B` is to apply `f` to an `A`.
        case Some(stb)   => stb(s2)._2                         // Here, we can get a value of type B.
        case None        => ??? // We are stuck: there is no way of returning a value of type B here.
    }
    ???                 )
}
\end{lstlisting}


\subsubsection{Example \label{subsec:Example-state-monad-composition-fails-with-reader}\ref{subsec:Example-state-monad-composition-fails-with-reader}}

Show that the \lstinline!State! monad fails to compose outside the
\lstinline!Reader! monad.

\subparagraph{Solution}

Begin by implementing \lstinline!pure! and \lstinline!flatMap! for
the type constructor \lstinline!State[S, R => A]!:
\begin{lstlisting}
type StR[A] = S => (R => A, S) // Here, the fixed types R and S must be already defined.
def pure[A](a: A): StR[A] = { s => (_ => a, s) }
def flatMap[A, B](fa: StR[A])(f: A => StR[B]): StR[B] = { s =>  // Need a value of type (R => B, S).
  val (s1, ra): (S, R => A) = fa(s)                  // We now have two values (s and s1) of type S.
  val rb: R => B = { r =>  // We can compute a value of type R => B. Trying to preserve information.
    val a: A = ra(r)
    val (s2, rb): (S, R => B) = f(a)(s1)
    rb(r)   // We must discard s2 here. This loses information since we could not use `f` elsewhere.
  }
  (rb, s1)  // We can only return (rb, s1) or (rb, s) here, since `s2` is not visible in this scope!
}
\end{lstlisting}
There is a problem with this implementation: The new state value $s_{1}$
is computed without using the function argument $f$. The only usage
of $f$ (producing $s_{2}$) is hidden within the scope of the nameless
function of type $R\rightarrow B$. So, even though we have tried
to preserve information as much as possible, the implementation of
\lstinline!flatMap! must discard the second monad\textsf{'}s effect. This
will violate the identity law \lstinline!pure(x).flatMap(f) == f(x)!.
That law cannot possibly hold if the implementation of \lstinline!flatMap!
ignores the function $f$ when computing the new state:

\begin{wrapfigure}{l}{0.38\columnwidth}%
\vspace{-1\baselineskip}
\begin{lstlisting}
pure(x).flatMap(f)
  == flatMap { s => (_ => x, s) } (f)
  == { s =>
  val (ra, s) = (_ => x, s)
  val rb = ...
  (rb, s)
}
\end{lstlisting}

\vspace{-1.5\baselineskip}
\end{wrapfigure}%

\noindent The result always has the initial unmodified \lstinline!s!
as the second element of the pair. However, $f$ is an arbitrary function
of type \lstinline!A => StR[B]!, so \lstinline!f(x): StR[B]! could
equal the function \lstinline!{ s => (... , p(x, s)) }!, where the
value \lstinline!p(x, s)! is not necessarily equal to \lstinline!s!.
Therefore, \lstinline!pure(x).flatMap(f)! is not equal to \lstinline!f(x)!
for arbitrary functions \lstinline!f!.

\subsection{Combining monads via monad transformers}

Not all monads combine with others via functor composition. But even
for those that do, the method used in Example~\ref{subsec:Example-lift-for-List-Try-composition}
requires writing custom wrapper classes for each\emph{ pair} of monads.
The length of the required code is then quadratic in the number of
supported monads. \textsf{``}Monad transformers\textsf{''} is an approach for organizing
the monad-combining code without incurring the quadratic growth of
the code size.

In this approach, we fix the first monad $L$ (the \textsf{``}\textbf{base}\textsf{''}
monad) and write code that combines $L$ with an \emph{arbitrary}
second monad $M$ (the \textsf{``}\textbf{foreign}\textsf{''} monad), implementing
a new monad denoted by $T_{L}^{M}$. It turns out that the code of
$T_{L}^{M}$ can be made fully parametric in the monad $M$: the \lstinline!pure!
and \lstinline!flatMap! methods of $T_{L}^{M}$ will use only $M$\textsf{'}s
monad methods ($\text{pu}_{M}$ and $\text{flm}_{M}$) and will work
in the same way for all foreign monads $M$. The monad $T_{L}^{M}$
is called \textsf{``}the monad $L$\textsf{'}s transformer applied to $M$\textsf{''}. So,
the \textbf{monad} $L$\textsf{'}s\textbf{ transformer} \index{monad transformers}is
the type constructor $T_{L}^{M,A}$ viewed as a function of its type
parameters $M$ and $A$. We say \emph{the} transformer $T_{L}^{M}$
(rather than \emph{a} transformer) because, as a rule, there is only
one way of defining $T_{L}^{M}$ (but see Section~\ref{subsec:Examples-of-monads-with-two-different-transformers}
below for some exceptions to that rule).

To illustrate this approach, let us implement the transformer for
the \lstinline!Try! monad. We begin with Example~\ref{subsec:Example-lift-for-List-Try-composition}
that combines \lstinline!Try! with \lstinline!List!, but we now
view \lstinline!Try! as the base monad and \lstinline!List! as the
foreign monad. The goal is to replace \lstinline!List! by an arbitrary
foreign monad $M$, so that the resulting code works in the same way
for all monads $M$. Begin by commenting the code of Example~\ref{subsec:Example-lift-for-List-Try-composition}
to indicate the usage of the \lstinline!List! monad\textsf{'}s methods \lstinline!pure!
and \lstinline!flatMap!:
\begin{lstlisting}
final case class ListTry[A](value: List[Try[A]]) { // We will use List.map, List.pure, List.flatMap.
  def map[B](f: A => B): ListTry[B] = ListTry(value.map(_.map(f)))           // Using List.map here.
  def flatMap[B](f: A => ListTry[B]): ListTry[B] = ListTry(
    value.flatMap {         // Using List.flatMap here.
      case Failure(t)   => List(Failure(t)) // This is List.pure(Failure(t)).
      case Success(a)   => f(a).value
    })
}
def pure[A](a: A): ListTry[A] = ListTry(List(Success(a)))          // This is List.pure(Success(a)).
\end{lstlisting}
It is now straightforward to generalize that code to an arbitrary
foreign monad $M$:
\begin{lstlisting}[mathescape=true]
final case class TryT[M[_]: Monad : Functor, A](value: M[Try[A]]) {
  def map[B](f: A => B): TryT[M, B] = TryT(value.map(_.map(f)))         // Using M$\color{dkgreen}\texttt{'}$s `map` here.
  def flatMap[B](f: A => TryT[M, B]): TryT[M, B] = TryT(
    value.flatMap {                                                 // Using M$\color{dkgreen} \texttt{'}$s `flatMap` here.
      case Failure(t)   => Monad[M].pure(Failure(t)) // Use Monad[M].pure(x) instead of List(x).
      case Success(a)   => f(a).value
    })
}
def pure[A](a: A): ListTry[A] = ListTry(Monad[M].pure(Success(a)))     // Using M$\color{dkgreen} \texttt{'}$s `pure` here.
\end{lstlisting}
The \textsf{``}foreign lift\textsf{''} and the \textsf{``}base lift\textsf{''} also use the methods
of the foreign monad $M$:
\begin{lstlisting}
implicit class TryTLift[M[_]: Monad : Functor, A](m: M[A]) {
  def up: TryT[M, A] = TryT(m.map(Success(_)))
}
implicit class TryTBaseLift[M[_]: Monad : Functor, A](t: Try[A]) {
  def up: TryT[M, A] = TryT(Monad[M].pure(t))
}
\end{lstlisting}
 After these definitions, we are able to combine \lstinline!Try!
with any other monad \lstinline!M!, as long as an implicit values
of type \lstinline!Monad[M]! and \lstinline!Functor[M]! are in scope.
The code will look like this:
\begin{lstlisting}
implicit val functorList: Functor[List] = ... // Create a Functor typeclass instance for List.
implicit val monadList: Monad[List] = ...     // Create a Monad typeclass instance for List.

scala> val result = for {
         x <- List(1, 2, 3).up
         y <- Try(x + 100).up
       } yield y
res0: TryT[List, Int] = TryT(List(Success(101), Success(102), Success(103)))
\end{lstlisting}

This example defines a type constructor denoted by $T_{\text{Try}}^{M,\bullet}$
that works parametrically in the foreign monad $M$. We can use $T_{\text{Try}}^{M,A}$
as a monad with respect to the type parameter $A$. (The foreign monad
$M$ is the first type parameter in the transformer.) We will later
implement transformers for other monads, such as $T_{\text{Reader}}^{M}$,
$T_{\text{Writer}}^{M}$, $T_{\text{State}}^{M}$, etc. The advantage
of the transformer approach is that the code for $T_{L}^{M}$ needs
to be written once for every base monad $L$, not for every pair of
monads $L$, $M$.

\subsection{Monad transformers for standard monads\label{subsec:Monad-transformers-for-standard-monads}}

While the code of \lstinline!TryT! works, it leaves us with further
questions. The code of \lstinline!TryT! is specific to the \lstinline!Try!
monad and uses its internal structure (the \lstinline!Failure! and
\lstinline!Success! subtypes). It is not obvious how to implement
a monad transformer $T_{L}^{M}$ for an arbitrary given base monad
$L$. We expect the code for $T_{L}^{M}$\textsf{'}s methods to be parametric
in $M$ but not in $L$ (this is reflected in the notation: $L$ is
a \emph{subscript} in $T_{L}^{M}$). So, changing the base monad $L$
to another monad forces a complete rewrite of $T_{L}^{M}$\textsf{'}s code.

There is no general recipe for implementing a monad transformer $T_{L}^{M}$
given the code for a monad $L$. Nevertheless, monad transformers
are known for every monad defined by fully parametric code. Transformers
for some monads are obtained via functor composition; for other monads,
transformers need to be defined in special ways. Table~\ref{tab:Known-monad-transformers}
lists the types of some known monad transformers. 

\begin{wraptable}{l}{0.59\columnwidth}%
\begin{centering}
\vspace{-0.1\baselineskip}
\begin{tabular}{|c|c|c|}
\hline 
\textbf{\small{}Name} & \textbf{\small{}Base monad} & \textbf{\small{}Transformer type}\tabularnewline
\hline 
\hline 
{\small{}}\lstinline!Reader! & {\small{}$L^{A}\triangleq R\rightarrow A$} & {\small{}$T_{L}^{M,A}\triangleq R\rightarrow M^{A}$}\tabularnewline
\hline 
{\small{}}\lstinline!Either! & {\small{}$L^{A}\triangleq Z+A$} & {\small{}$T_{L}^{M,A}\triangleq M^{Z+A}$}\tabularnewline
\hline 
{\small{}}\lstinline!Writer! & {\small{}$L^{A}\triangleq A\times W$} & {\small{}$T_{L}^{M,A}\triangleq M^{A\times W}$}\tabularnewline
\hline 
{\small{}}\lstinline!List! & {\small{}$L^{A}\triangleq\bbnum 1+A\times L^{A}$} & {\small{}$T_{L}^{M,A}\triangleq M^{\bbnum 1+A\times T_{L}^{M,A}}$}\tabularnewline
\hline 
{\small{}}\lstinline!Eval! & {\small{}$L^{A}\triangleq A+\left(\bbnum 1\rightarrow A\right)$} & {\small{}$T_{L}^{M,A}\triangleq M^{A+(\bbnum 1\rightarrow M^{A})}$}\tabularnewline
\hline 
{\small{}}\lstinline!State! & {\small{}$L^{A}\triangleq S\rightarrow A\times S$} & {\small{}$T_{L}^{M,A}\triangleq S\rightarrow M^{A\times S}$}\tabularnewline
\hline 
{\small{}}\lstinline!Cont! & {\small{}$L^{A}\triangleq\left(A\rightarrow R\right)\rightarrow R$} & {\small{}$T_{L}^{M,A}\triangleq(A\rightarrow M^{R})\rightarrow M^{R}$}\tabularnewline
\hline 
{\small{}}\lstinline!Sel! & {\small{}$L^{A}\triangleq\left(A\rightarrow R\right)\rightarrow A$} & {\small{}$T_{L}^{M,A}\triangleq(M^{A}\rightarrow R)\rightarrow M^{A}$}\tabularnewline
\hline 
\end{tabular}
\par\end{centering}
\caption{\label{tab:Known-monad-transformers}Known monad transformers for
some monads.}
\vspace{-0.6\baselineskip}
\end{wraptable}%

\noindent Depending on the monad, the corresponding transformer is
defined by composing inside the foreign monad (\lstinline!Either!,
\lstinline!Writer!); by composing outside the foreign monad (\lstinline!Reader!,
\lstinline!Sel!); by wrapping a recursive definition inside the foreign
monad (\lstinline!List!); and by mixing the foreign monad in a special
way with the base monad (\lstinline!Eval!, \lstinline!State!, \lstinline!Cont!). 

It is not easy to guess the type of a monad transformer.\footnote{The difficulty of that task is illustrated by the history of the \lstinline!ListT!
transformer in the Haskell standard library. The transformer \lstinline!ListT!
was implemented incorrectly in 2002; the code violated the monad laws.
The faulty transformer remained in the library until 2007. See the
discussion in \texttt{\href{https://wiki.haskell.org/index.php?title=ListT_done_right}{https://wiki.haskell.org/index.php?title=ListT\_done\_right}}} A justification for the types in Table~\ref{tab:Known-monad-transformers}
is that they work and obey the required laws, while no simpler transformers
are known. We will prove the required laws for these and other transformers
later in this chapter. For now, we accept the results of Table~\ref{tab:Known-monad-transformers}
and turn to the practical use of monad transformers. 

The first task is to obtain the code of monad methods and lifts for
the transformers in Table~\ref{tab:Known-monad-transformers}.

The type constructors for monad transformers are conventionally named
\lstinline!ReaderT!, \lstinline!EitherT!, etc. 

\paragraph{The \texttt{ReaderT} transformer}

The corresponding monad was already derived in Statement~\ref{subsec:Statement-monad-construction-1}:
\begin{lstlisting}
final case class ReaderT[M[_]: Monad : Functor, R, A](run: R => M[A]) {
  def map[B](f: A => B): ReaderT[M, R, B] = ReaderT(r => run(r).map(f))
  def flatMap[B](f: A => ReaderT[M, R, B]): ReaderT[M, R, B] = ReaderT {
    r => run(r)            // Type is M[A].
           .flatMap(f)     // Type is M[ReaderT[M, R, B]].
           .map(_.run(r))  // Type is M[B].
  }
}
def pure[M[_]: Monad, A](a: A): ReaderT[M, A] = ReaderT(_ => Monad[M].pure(a))
\end{lstlisting}
The \textsf{``}foreign lift\textsf{''} and the \textsf{``}base lift\textsf{''} for \lstinline!ReaderT!
are implemented by
\begin{lstlisting}
implicit class ReaderTLift[M[_]: Monad : Functor, R, A](m: M[A]) {
  def up: ReaderT[M, R, A] = ReaderT(_ => m) // This is the `pure` method of the Reader monad.
}
implicit class ReaderTBaseLift[M[_]: Monad : Functor, R, A](t: R => A) {
  def up: ReaderT[M, R, A] = ReaderT(r => Monad[M].pure(t(r)))
}
\end{lstlisting}
The lifts are written in the code notation as
\begin{align*}
{\color{greenunder}\text{foreign lift}:}\quad & \text{flift}:M^{A}\rightarrow T_{\text{Reader}}^{M,A}\quad, & \text{flift}\,(m^{:M^{A}})\triangleq\_^{:R}\rightarrow m=\text{pu}_{\text{Reader}}(m)\quad,\quad~\\
{\color{greenunder}\text{base lift}:}\quad & \text{blift}:(R\rightarrow A)\rightarrow T_{\text{Reader}}^{M,A}\quad, & \text{blift}\,(t^{:R\rightarrow A})\triangleq r^{:R}\rightarrow\text{pu}_{M}(t(r))=t\bef\text{pu}_{M}\quad.
\end{align*}

We have seen in Section~\ref{subsec:The-Reader-monad} that getting
data out of the \lstinline!Reader! monad requires a runner ($\theta_{\text{Reader}}$),
which is a function that calls \lstinline!run! on some value of type
$R$ (i.e., injects \lstinline!Reader!\textsf{'}s dependency value). In later
sections~\ref{subsec:The-State-monad} and~\ref{subsec:The-continuation-monad},
we have seen other monads that need runners. Generally, a runner for
a monad $M$ is a function of type $M^{A}\rightarrow A$. So, we may
expect that the foreign monad $M$ could have its own runner ($\theta_{M}:M^{A}\rightarrow A$).
How can we combine $M$\textsf{'}s runner ($\theta_{M}$) with \lstinline!Reader!\textsf{'}s
runner? Since the type of $T_{\text{Reader}}^{M}$ is a functor composition
of \lstinline!Reader! and $M$, the runners can be used independently
of each other. We can first run the effect of $M$ and then run the
effect of \lstinline!Reader!:
\[
(\theta_{M}^{\uparrow\text{Reader}}\bef\theta_{\text{Reader}}):(R\rightarrow M^{A})\rightarrow A\quad.
\]
Alternatively, we can run \lstinline!Reader!\textsf{'}s effect first (injecting
the dependency) and then run $M$\textsf{'}s effect:
\[
(\theta_{\text{Reader}}\bef\theta_{M}):(R\rightarrow M^{A})\rightarrow A\quad.
\]
These runners commute because of the naturality law of $\theta_{\text{Reader}}$,
which holds for any $f^{:A\rightarrow B}$:
\[
f^{\uparrow\text{Reader}}\bef\theta_{\text{Reader}}=\theta_{\text{Reader}}\bef f\quad,\quad\text{so}\quad\theta_{M}^{\uparrow\text{Reader}}\bef\theta_{\text{Reader}}=\theta_{\text{Reader}}\bef\theta_{M}\quad.
\]


\paragraph{The \texttt{EitherT} transformer}

is similar to \lstinline!TryT! since the type \lstinline!Try[A]!
is equivalent to \lstinline!Either[Throwable, A]!.

\paragraph{The \texttt{WriterT} transformer}

It is easier to begin with the \lstinline!flatten! method for the
transformed monad $T^{A}\triangleq M^{A\times W}$, which has type
signature
\[
\text{ftn}_{T}:M^{M^{A\times W}\times W}\rightarrow M^{A\times W}\quad,\quad\quad\text{ftn}_{T}\big(t^{:M^{M^{A\times W}\times W}}\big)=\text{???}^{:M^{A\times W}}\quad.
\]
Since $M$ is an unknown, arbitrary monad, the only way of computing
a value of type $M^{A\times W}$ is by using the given value $t$
somehow. The only way to get a value of type $A$ wrapped in $M^{A\times W}$
is by extracting the type $A$ from inside $M^{M^{A...}...}$. So,
we need to flatten the two layers of $M$ that are present in the
type of $t$. However, we cannot immediately apply $M$\textsf{'}s \lstinline!flatten!
method to $t$ because $t$\textsf{'}s type is not of the form $M^{M^{X}}$
with some $X$. To bring it to that form, we use $M$\textsf{'}s \lstinline!map!
method:
\[
t\triangleright(m^{:M^{A\times W}}\times w^{:W}\rightarrow m\triangleright(p^{:A\times W}\rightarrow p\times w)^{\uparrow M})^{\uparrow M}:M^{M^{A\times W\times W}}\quad.
\]
Now the type is well adapted to using both $M$\textsf{'}s and \lstinline!Writer!\textsf{'}s
flatten methods:
\begin{align*}
\text{ftn}_{T}\big(t^{:M^{M^{A\times W}\times W}}\big) & =t\triangleright(m^{:M^{A\times W}}\times w^{:W}\rightarrow m\triangleright(p^{:A\times W}\rightarrow p\times w)^{\uparrow M})^{\uparrow M}\triangleright\text{ftn}_{M}\triangleright(\text{ftn}_{\text{Writer}})^{\uparrow M}\quad,\\
\text{ftn}_{T} & =(m^{:M^{A\times W}}\times w^{:W}\rightarrow m\triangleright(p^{:A\times W}\rightarrow p\times w)^{\uparrow M})^{\uparrow M}\bef\text{ftn}_{M}\bef(\text{ftn}_{\text{Writer}})^{\uparrow M}\\
 & =\text{flm}_{M}(m\times w\rightarrow m\triangleright(p\rightarrow p\times w)^{\uparrow M}\bef\text{ftn}_{\text{Writer}}^{\uparrow M})\\
 & =\text{flm}_{M}(m\times w\rightarrow m\triangleright(a\times w_{2}\rightarrow a\times(w\oplus w_{2})))\quad.
\end{align*}

Translating this formula to Scala, we obtain the code of \lstinline!flatMap!:
\begin{lstlisting}
final case class WriterT[M[_]: Monad : Functor, W: Monoid, A](t: M[(A, W)]) {
  def map[B](f: A => B): WriterT[M, W, B] = WriterT(t.map { case (a, w) => (f(a), w) })
  def flatMap[B](f: A => WriterT[M, W, B]): WriterT[M, W, B] = WriterT(
    t.flatMap { case (a, w) => f(a).t.map { case (b, w2) => (b, w |+| w2) }  
  })
}  
\end{lstlisting}
The code of \lstinline!pure! is straightforward:
\begin{lstlisting}
def pure[M[_]: Monad, W: Monoid, A](a: A): WriterT[M, W, A] =
  WriterT(Monad[M].pure((a, Monoid[W].empty))
\end{lstlisting}
The \textsf{``}foreign lift\textsf{''} and the \textsf{``}base lift\textsf{''} for \lstinline!WriterT!
are:
\begin{lstlisting}
def flift[A]: M[A] => M[(A, W)] = _.map { a => (a, Monoid[W].empty) }
def blift[A]: ((A, W)) => M[(A, W)] = { t => Monad[M].pure(t) }
\end{lstlisting}
\begin{align*}
{\color{greenunder}\text{foreign lift}:}\quad & \text{flift}:M^{A}\rightarrow T_{\text{Writer}}^{M,A}\quad,\quad\quad m^{:M^{A}}\triangleright\text{flift}\triangleq m\triangleright(a\rightarrow a\times e_{w})^{\uparrow M}\quad,\\
{\color{greenunder}\text{base lift}:}\quad & \text{blift}:\text{Writer}^{W,A}\rightarrow T_{\text{Writer}}^{M,A}\quad,\quad\quad\text{blift}\triangleq\text{pu}_{M}\quad.
\end{align*}

Comparing the lifts for \lstinline!ReaderT! and \lstinline!WriterT!,
we notice some common features of lifts for compositional transformers
(\lstinline!ReaderT!, \lstinline!EitherT!, \lstinline!WriterT!):
one of the lifts is equal to a \lstinline!pure! method, and the other
is equal to a lifted \lstinline!pure! method. We will see later that
this pattern applies to all monad transformers defined via functor
composition.

\paragraph{The \texttt{ListT} transformer}

is more complicated because \lstinline!List! is a recursive type.
To shorten the code, we use the \lstinline!Option! type to represent
$\bbnum 1+A\times T_{\text{List}}^{M,A}$ in the recursive type $T_{\text{List}}^{M,A}\triangleq M^{\bbnum 1+A\times T_{\text{List}}^{M,A}}$:
\begin{lstlisting}
final case class ListT[M[_]: Monad : Functor, A](value: M[Option[(A, ListT[M, A])]])
\end{lstlisting}
The \lstinline!List! monad was implemented in Example~\ref{subsec:Example-flatten-verify-for-monad-1-1}
using the list concatenation function \lstinline!concat!; \textsf{``}flattening\textsf{''}
a \lstinline!List[List[A]]! means concatenating all nested lists.
If the ordinary \lstinline!List! were defined via \lstinline!Option!,
the code for \lstinline!concat! would be
\begin{lstlisting}
final case class ListO[A](value: Option[(A, ListO[A])])
def concat[A](t1: ListO[A], t2: ListO[A]): ListO[A] = t1.value match {
  case None => t2
  case Some((a, tail)) => Some((a, concat(tail, t2))) // Recursive call.
}
\end{lstlisting}
We need to implement the analogous concatenation function for \lstinline!ListT!.
To visualize the type of \lstinline!ListT!, consider an example where
the foreign monad is $M^{A}\triangleq R\rightarrow A$. Expand a few
steps of recursion:
\[
T_{\text{List}}^{M,A}=R\rightarrow\bbnum 1+A\times(R\rightarrow\bbnum 1+A\times(R\rightarrow...(R\rightarrow\bbnum 1+A\times T_{\text{List}}^{M,A})...))\quad.
\]
This type describes an $M$-effect wrapped around each next value
of type $A$ in the list. To extract further values in the list, we
need to run the nested effects.

This understanding helps us implement the concatenation function for
\lstinline!ListT!, called \lstinline!comb!:
\begin{lstlisting}
def comb[M[_]: Monad : Functor, A](t1: ListT[M, A], t2: ListT[M, A]): ListT[M, A] = ListT( for {
  first <- t1.value           // Run the first effect and get `first: Option[(A, ListT[M, A])]`.
  rest  = first match {       // Compute `rest: M[Option[(A, ListT[M, A])]]`.
           case None => t2.value
           case Some((a, tail)) => Monad[M].pure(Some((a, comb(tail, t2))))   // Recursive call.
  y     <- rest
} yield y)
\end{lstlisting}

We are now ready to write the code of \lstinline!ListT!\textsf{'}s \lstinline!flatMap!
method:
\begin{lstlisting}
final case class ListT[M[_]: Monad : Functor, A](value: M[Option[(A, ListT[M, A])]]) {
  def map[B](f: A => B): ListT[M, B] = ListT(t.map(_.map { // Use the map methods of M and Option.
    case (head, tail) => (f(head), tail.map(f))
  }))
  def flatMap[B](f: A => ListT[M, B]): ListT[M, B] = ListT(
    t.flatMap {    // Here we need a function of type Option[(A, ListT)] => M[Option[(A, ListT)]].
      case None => Monad[M].pure(None)
      case Some((head, tail)) => comb(f(head), tail).value       // Type is M[Option[(A, ListT)]].
  })
}
\end{lstlisting}
The code of \lstinline!pure! creates a single-element list, which
uses a pair of an $a^{:A}$ and an empty list:
\begin{lstlisting}
def pure[M[_]: Monad, A](a: A): ListT[M, A] =
  ListT(Monad[M].pure(Some((a, ListT(Monad[M].pure(None))))))
\end{lstlisting}
The lifts for \lstinline!ListT! are:
\begin{lstlisting}
def flift[M[_]: Monad, A]: M[A] => ListT[M, A] = ListT(a => m.flatMap(ListT.pure(a).value))
def blift[M[_]: Monad, A]: List[A] => ListT[M, A] =
  _.foldRight(Monad[M].pure(None)){ case (a, tail) => Monad[M].pure(Some((a, blift(tail)))) }
\end{lstlisting}
\begin{align*}
{\color{greenunder}\text{foreign lift}:}\quad & \text{flift}:M^{A}\rightarrow T_{\text{List}}^{M,A}\quad,\quad\quad m^{:M^{A}}\triangleright\text{flift}\triangleq m\triangleright(a\rightarrow\bbnum 0+a\times\text{pu}_{M}(1+\bbnum 0))^{\uparrow M}\quad,\\
{\color{greenunder}\text{base lift}:}\quad & \text{blift}:\text{List}^{A}\rightarrow T_{\text{List}}^{M,A}\quad,\quad\quad\text{blift}\triangleq\,\begin{array}{|c||c|}
 & M^{\bbnum 1+A\times T_{\text{List}}^{M,A}}\\
\hline \bbnum 1 & 1\rightarrow\text{pu}_{M}(1+\bbnum 0)\\
A\times\text{List}^{A} & a\times t\rightarrow\text{pu}_{M}(\bbnum 0+a\times\overline{\text{blift}}\,(t))
\end{array}\quad.
\end{align*}

Finally, we turn to runners for \lstinline!ListT!. List-like monads
usually represent \emph{several} useful results rather than a single
result. So, they may not need runners of type $\text{List}^{A}\rightarrow A$.
Also, a list may be empty, which makes a fully parametric function
of type $\text{List}^{A}\rightarrow A$ impossible. However, the foreign
monad $M$ may come with its runner $\theta_{M}$. We can use $\theta_{M}$
to run the $M$\textsf{'}s effects and extract values from a \lstinline!ListT!.
This is accomplished by a runner (call it \lstinline!runListT!) that
applies $M$\textsf{'}s runner ($\theta_{M}$) to a value of type \lstinline!ListT[M, A]!
and obtains a \lstinline!List[A]!. The code may be written as:
\begin{lstlisting}
def runListT[A](runner: M[A] => A)(listT: ListT[M, A]): List[A] = runner(listT.value) match {
  case None                => List()
  case Some((head, tail))  => head :: run(runner)(tail)
}
\end{lstlisting}
However, this code will not always terminate. The reason is that the
type of \lstinline!ListT! contains a layer of $M$ in every recursive
step. So, extracting a value of type \lstinline!List[A]! from a value
of type \lstinline!ListT[M, A]! involves applying $\theta_{M}$ once
per list value. When $M$ is of function type, a value of type \lstinline!ListT[M, A]!
is an \textsf{``}on-call\textsf{''}\index{on-call value} sequence whose elements
are not available in advance but will be evaluated on demand when
$\theta_{M}$ is applied. So, the total number of elements in \lstinline!ListT!
may not be known in advance and may be infinite. An example of an
\textsf{``}infinite\textsf{''} collection uses the \lstinline!Reader! monad as $M$:
\begin{lstlisting}
def ascend(a: Int): ListT[Reader[Int, *], Int] = ListT(Lazy(k => Some((a, ascend(a + k)))))
\end{lstlisting}
This is a well-defined value of type \lstinline!ListT! that represents
integer sequences $\left[a,a+k,a+2k,...\right]$. The parameter $k$
is passed via the \lstinline!Reader! monad\textsf{'}s dependency injection.
It is clear that \lstinline!runListT! will not terminate when applied
to such a sequence. 

This example shows how to use \lstinline!ListT! for creating effectful
streams of unbounded length. If we need to run the effects of $M$
for an unbounded-length stream, the target should be a stream type
(i.e., an on-call or a lazy list) rather than an eagerly evaluated
\lstinline!List! type.

Another way of running the effects of a \lstinline!ListT[M, A]! is
to assume that \lstinline!A! is a monoid type. For monoid types \lstinline!A!,
we can implement the type signature $\text{List}^{A}\rightarrow A$
as a standard \lstinline!reduce! operation:
\begin{lstlisting}
def reduce[A: Monoid]: List[A] => A = {
  case Nil            => Monoid[A].empty
  case head :: tail   => head |+| reduce(tail)
}
\end{lstlisting}
Similar code gives a runner \lstinline!brun! that transforms \lstinline!ListT[M, A]!
into \lstinline!M[A]! for monoid types \lstinline!A!:
\begin{lstlisting}
def brun[M[_]: Monad, A: Monoid](listT: ListT[M, A]): M[A] = listT.value.flatMap {
  case None                  => Monad[M].pure(Monoid[A].empty)
  case Some((head, tail))    => Monad[M].pure(head) |+| brun(tail) // Monoid M[A].
}
\end{lstlisting}
For this code to work, we need a monoid instance for $M^{A}$ (see
Exercise~\ref{subsec:Exercise-monad-of-monoid-is-monoid}):
\begin{lstlisting}
implicit def monoidMA[M[_]: Functor : Monad, A: Monoid]: Monoid[M[A]] = ...
\end{lstlisting}
However, it remains unknown\footnote{This book does not have a proof. See Problem~\ref{par:Problem-monads-5-2-1}
for more details.} whether this special version of \lstinline!brun! is a lawful monad
morphism $T_{\text{List}}^{M}\leadsto M$ or even just a monoid morphism
$T_{\text{List}}^{M,A}\rightarrow M^{A}$.

\paragraph{The \texttt{StateT} transformer}

The formula for that transformer\textsf{'}s type, \lstinline!StateT[M, S, A] = S => M[(S, A)]!,
puts the foreign monad $M$ at a specific place within the type of
the \lstinline!State! monad. Let us implement the monad methods for
\lstinline!StateT!:
\begin{lstlisting}
final case class StateT[M[_]: Monad : Functor, S, A](run: S => M[(A, S)]) {
  def map[B](f: A => B): StateT[M, S, B] = StateT(s1 => run(s1).map { // Use the map method of M.
    case (a, s2) => (f(a), s2)
  })
  def flatMap[B](f: A => StateT[M, S, B]): StateT[M, S, B] = StateT(s1 => run(s1).flatMap {
      case (a, s2) => f(a).run(s2)                // Use the updated intermediate state s2.
  })
}
def pure[M[_]: Monad, S, A](a: A): StateT[M, S, A] = StateT(s => Monad[M].pure((a, s)))
\end{lstlisting}
\begin{align}
 & T_{\text{State}}^{M,A}\triangleq T^{A}\triangleq S\rightarrow M^{A\times S}\quad,\quad\quad\text{pu}_{T}\triangleq a^{:A}\rightarrow s^{:S}\rightarrow\text{pu}_{M}(a\times s)\quad,\label{eq:pure-for-stateT-transformer}\\
 & \text{flm}_{T}(f^{:A\rightarrow T^{B}})\triangleq t^{:T^{A}}\rightarrow s_{1}^{:S}\rightarrow t(s_{1})\triangleright\text{flm}_{M}(a\times s_{2}\rightarrow f(a)(s_{2}))\quad.\label{eq:flatmap-for-stateT-transformer}
\end{align}

The implementations of the lift functions for \lstinline!StateT!
are:
\begin{lstlisting}
def flift[M[_]: Functor, S, A](m: M[A]): StateT[M, S, A] = StateT(s => m.map { a => (a, s) })
def blift[M[_]: Monad, S, A](p: State[S, A]): StateT[M, S, A] = StateT(s => Monad[M].pure(p.run(s)))
\end{lstlisting}
\begin{align*}
{\color{greenunder}\text{foreign lift}:}\quad & \text{flift}:M^{A}\rightarrow T_{\text{State}}^{M,A}\quad,\quad\quad m^{:M^{A}}\triangleright\text{flift}\triangleq s\rightarrow m\triangleright(a\rightarrow a\times s)^{\uparrow M}\quad,\\
{\color{greenunder}\text{base lift}:}\quad & \text{blift}:(S\rightarrow A\times S)\rightarrow T_{\text{State}}^{M,A}\quad,\quad\quad\text{blift}\triangleq p^{:S\rightarrow A\times S}\rightarrow p\bef\text{pu}_{M}\quad.
\end{align*}

The \lstinline!State! monad\textsf{'}s runner ($\theta_{\text{State}}$) substitutes
a given initial state and extracts the final value:
\begin{lstlisting}
def runState[S, A](init: S)(p: State[S, A]): A = p.run(init)._1
\end{lstlisting}
\[
\theta_{\text{State}}(i^{:S})\triangleq p^{:S\rightarrow A\times S}\rightarrow i\triangleright p\triangleright\pi_{1}\quad.
\]

The transformer \lstinline!StateT! does not have a general base runner
of the form $\text{brun}\,(\theta_{\text{State}})$ converting an
\emph{arbitrary} runner $\theta_{\text{State}}:\text{State}^{S,A}\rightarrow A$
into a function of type $T_{\text{State}}^{M,A}\rightarrow M^{A}$.
Instead, we need to implement a specialized base runner that converts
$T_{\text{State}}^{M,A}$ into $M^{A}$ directly, running the \lstinline!State!
monad\textsf{'}s effects but keeping the effects of the foreign monad $M$:
\begin{lstlisting}
def brunStateT[M[_]: Functor, S, A](init: S)(t: StateT[M, S, A]): M[A] = t.run(init).map(_._1)
\end{lstlisting}
\[
\text{brun}_{\text{State}}(i^{:S})\triangleq t^{S\rightarrow M^{A\times S}}\rightarrow i\triangleright t\triangleright\pi_{1}^{\uparrow M}\quad.
\]
If we need to run only the effects of $M$ but keep the \lstinline!State!
monad\textsf{'}s effect, we need the following code:
\begin{lstlisting}
def frunStateT[M[_], S, A](runner: M[A] => A)(t: StateT[M, S, A]): State[S, A] = State { s =>
  val m: M[(A, S)] = t.run(s)
  runner(m)
}
\end{lstlisting}
\[
\text{frun}_{\text{State}}(\theta^{:M^{A}\rightarrow A})\triangleq t^{:S\rightarrow M^{A\times S}}\rightarrow\left(s\rightarrow s\triangleright t\bef\theta\right)=t^{:S\rightarrow M^{A\times S}}\rightarrow t\bef\theta\quad.
\]


\paragraph{The \texttt{ContT} transformer}

For the continuation monad (\lstinline!Cont[R, A]!), the transformer\textsf{'}s
type constructor \lstinline!ContT[M, R, A]! has a peculiar formula
where the foreign monad\textsf{'}s constructor $M$ wraps the type $R$ but
is not applied to any values of the main value type $A$. The code
for the monad methods is:
\begin{lstlisting}
final case class ContT[M[_], R, A](run: (A => M[R]) => M[R]) {
  def map[B](f: A => B): ContT[M, R, B] = ContT { (k: B => M[R]) => run(f andThen k) }
  def flatMap[B](f: A => ContT[M, R, B]): ContT[M, R, B] = ContT { (k: B => M[R]) =>
    val g: A => M[R] = a => f(a).run(k)
    run(g) 
  }
}
def pure[M[_], R, A](a: A): ContT[M, R, A] = ContT(k => k(a))
\end{lstlisting}

Turning now to the code for lifts, we can easily write the \textsf{``}foreign
lift\textsf{''}:
\begin{lstlisting}
def flift[M[_]: Monad, R, A](m: M[A]): ContT[M, R, A] = ContT { (k: A => M[R]) => m.flatMap(k) }
\end{lstlisting}
\[
\text{flift}:M^{A}\rightarrow(A\rightarrow M^{R})\rightarrow M^{R}=\text{flm}_{M}\quad.
\]
However, implementing the \textsf{``}base lift\textsf{''} is impossible: the required
type signature
\[
\text{blift}:(\left(A\rightarrow R\right)\rightarrow R)\rightarrow(A\rightarrow M^{R})\rightarrow M^{R}
\]
has no implementation parametric in the monad $M$. The reason is
that we cannot produce a value of type $R$ out of $M^{R}$ parametrically
(some monads have no runners), and so we cannot convert $A\rightarrow M^{R}$
into $A\rightarrow R$. This prevents us from using the first argument
of \lstinline!blift! (a function of type $(A\rightarrow R)\rightarrow R$),
while creating a value of type $(A\rightarrow M^{R})\rightarrow M^{R}$
from scratch is impossible. 

To produce an explicit example where \lstinline!blift! cannot be
implemented, we use the \texttt{curryhoward} library and choose a
monad $M^{R}$ that has no fully parametric runner, e.g., $M^{R}\triangleq Z+R$:
\begin{lstlisting}
import io.chymyst.ch._

scala> def blift[R, A]: Cont[R, A] => ContT[Either[Int, *], R, A] = implement
Error:(43, 65) type ((A => R) => R) => (A => Either[<c>Int,R]) => Either[<c>Int,R] cannot be implemented
\end{lstlisting}

The absence of \textsf{``}base lift\textsf{''} for the continuation monad transformer
means that we cannot use the continuation monad in a functor block
as freely as other monads. We cannot lift an arbitrary given value
of type \lstinline!Cont[R, A]! into the transformed monad \lstinline!ContT[M, R, A]!.
Concrete values of type \lstinline!Cont[R, A]! may result from calling
third-party libraries implemented in non-fully-parametric code. It
may be impossible to rewrite that code to return \lstinline!ContT[M, R, A]!
with an arbitrary monad \lstinline!M!. This deficiency of the continuation
monad makes it unsuitable for certain applications. 

The continuation monad also does not support foreign runners or base
runners. The type signature of the method $\text{frun}:T_{\text{Cont}}^{M,A}\rightarrow T_{\text{Cont}}^{N,A}$
cannot be implemented with arbitrary monads $M$, $N$ because the
type $T_{\text{Cont}}^{M,A}\triangleq(A\rightarrow M^{R})\rightarrow M^{R}$
is not covariant in the type parameter $M$. The base runner\textsf{'}s type
signature, $\text{brun}:((A\rightarrow M^{R})\rightarrow M^{R})\rightarrow M^{A}$,
cannot be implemented because there is no way of constructing a value
of type $M^{A}$ out of a value of type $M^{R}$ (the type $A$ is
arbitrary).

\paragraph{The \texttt{SelT} transformer}

Although the selector monad, $\text{Sel}^{Z,A}\triangleq\left(A\rightarrow Z\right)\rightarrow A$,
resembles the continuation monad, its transformer is simpler because
it consists of composing outside the foreign monad $M$ (i.e., we
replace $A$ by $M^{A}$ in the type of \lstinline!Sel!). Only one
implementation fits the type signatures:
\begin{lstlisting}
final case class SelT[M[_]: Monad : Functor, Z, A](run: (M[A] => Z) => M[A]) {
  def map[B](f: A => B): SelT[M,Z,B] = SelT { (mbz: M[B] => Z) => run(ma => mbz(ma.map(f))).map(f) }
  def flatMap[B](f: A => Sel[M, Z, B]): Sel[M, Z, B] = SelT { (mbz: M[B] => Z) =>
    val amb: A => M[B] = a => f(a).run(mbz)
    val maz: M[A] => Z = ma => mbz(ma.flatMap(amb))
    run(maz).flatMap(amb)
  }
}
def pure[M[_]: Monad, Z, A](a: A): SelT[M, Z, A] = SelT(_ => Monad[M].pure(a))
\end{lstlisting}
Since $T_{\text{Sel}}^{M}=\text{Sel}\circ M$ is a functor composition,
the lifts and the runners work as in the \lstinline!Reader! monad:
\begin{lstlisting}
def flift[A](m: M[A]): SelT[M, Z, A] = SelT(_ => m)   // Using the `pure` method of the Sel monad.
def blift[A](sel: Sel[Z, A]): SelT[M, Z, A] = SelT { (k: M[A] => Z) =>
  val az: A => Z = Monad[M].pure andThen k
  Monad[M].pure(sel(az))
}
\end{lstlisting}


\paragraph{The \texttt{EvalT} transformer}

The evaluation monad $\text{Eval}^{A}\triangleq A+\left(\bbnum 1\rightarrow A\right)$
described in Section~\ref{subsec:The-eager-lazy-evaluation-monad}
represents a choice of eager or lazy evaluation. The corresponding
transformer is defined by
\[
T_{\text{Eval}}^{M,A}\triangleq M^{A+(\bbnum 1\rightarrow M^{A})}\quad.
\]
Let us implement the \lstinline!EvalT! monad using \lstinline!Either!
and write the monad methods. The code for the \lstinline!Eval! monad
in Section~\ref{subsec:The-eager-lazy-evaluation-monad} used a helper
function \lstinline!get: Eval[A] => A!. We see that \lstinline!get!
is \lstinline!Eval!\textsf{'}s runner. A similar function (\lstinline!brun!)
plays the role of the \textsf{``}base runner\textsf{''} for \lstinline!EvalT!: it
runs \lstinline!Eval!\textsf{'}s effect (converting lazy values into eager
ones) but keeps $M$\textsf{'}s effects intact. We use \lstinline!brun! to
implement \lstinline!flatMap!:
\begin{lstlisting}
final case class EvalT[M[_]: Monad : Functor, A](value: M[Either[A, Unit => M[A]]]) {
  def map[B](f: A => B): EvalT[M, B] = EvalT(value.map {
    case Left(a)    => Left(f(a))
    case Right(g)   => Right(_ => g(()).map(f))
  })
  def flatMap[B](f: A => EvalT[M, B]): EvalT[M, B] = EvalT(value.flatMap {
    case Left(a)   => f(a).value
    case Right(g)  => Monad[M].pure(Right { _ => g(()).flatMap(a => EvalT.brun(f(a).value)) })
  })
}
object EvalT {
  def pure[M[_]: Monad, A](a: A): EvalT[M, A] = EvalT(Monad[M].pure(Left(a)))
  def brun[M[_]: Monad, A]: EvalT[M, A] => M[A] = _.value.flatMap { // Either[A, Unit=>M[A]] => M[A]
    case Left(a)   => Monad[M].pure(a)
    case Right(g)  => g(())
  }
}
\end{lstlisting}

The lifts are implemented straightforwardly:
\begin{lstlisting}
def flift[A](m: M[A]): EvalT[M, A] = EvalT(m.map(a => Left(a))) // `Left(a)` means `Eval.pure(a)`.
def blift[A](e: Either[A, Unit => A]): EvalT[M, A] = EvalT(Monad[M].pure(e match {
  case Left(a)   => Left(a)
  case Right(g)  => Right { _ => Monad[M].pure(g(())) } 
}))
\end{lstlisting}

Given a runner for $M$, we can run $M$\textsf{'}s effects while keeping \lstinline!Eval!\textsf{'}s
effects intact:
\begin{lstlisting}
def runEvalT[A](runner: M[A] => A)(t: EvalT[M, A]): Eval[A] = runner(t) match {
  case Left(a)    => Eager(a)                     // An eager value is ready.
  case Right(g)   => Lazy(_ => runner(g(())))     // A lazy value remains lazy.
}
\end{lstlisting}


\subsection{Combining more than two monads: monad stacks\label{subsec:Combining-more-than-monad-stacks}}

How can we combine \emph{three or more} monads in a single functor
block? For example, we may want somehow to make the following code
work:

\begin{wrapfigure}{l}{0.38\columnwidth}%
\vspace{-0.5\baselineskip}
\begin{lstlisting}
for {   // Could this code compile?
  i <- List(1, 2, 3).up
  j <- Writer(...).up
  x <- Try(i + j + 100).up
  y <- Future(x / 2).up
  z <- Reader(...).up
} yield z
\end{lstlisting}

\vspace{-1.2\baselineskip}
\end{wrapfigure}%

\noindent A monad transformer combines a base monad $L$ with any
given foreign monad $M$. The result is a new, \textsf{``}larger\textsf{''} monad
$T_{L}^{M}$ that can describe the effects of both $L$ and $M$.
To combine the monad $T_{L}^{M}$ with a third monad (say, $K$),
we could use $K$\textsf{'}s transformer and obtain the monad $T_{K}^{T_{L}^{M}}$
that describes the effects of $K$, $L$, and $M$. This technique
is known as making a \index{monads!stack of}\textbf{stack} of monads.

As an example, let us build a stack of \lstinline!Reader!, \lstinline!Writer!,
and \lstinline!State! monads. We set $K^{\bullet}=\text{Reader}^{R,\bullet}$,
$L^{\bullet}=\text{Writer}^{W,\bullet}$, and $M^{\bullet}=\text{State}^{S,\bullet}$,
and begin with $T_{L}^{M}$. Since the \lstinline!Writer!\textsf{'}s transformer
composes inside the foreign monad, we write $T_{\text{Writer}}^{\text{State},A}=S\rightarrow A\times W\times S$.
Now we apply the \lstinline!Reader!\textsf{'}s transformer, which composes
outside the foreign monad:
\[
T_{\text{Reader}}^{T_{\text{Writer}}^{\text{State},A}}=R\rightarrow S\rightarrow A\times W\times S\quad.
\]
This monad has an injected dependency of type $R$, an internally
maintained state of type $S$, and an output value of type $W$. A
value of type $R\rightarrow S\rightarrow A\times W\times S$ describes
all three effects at once.

If the transformers \lstinline!ReaderT! and \lstinline!WriterT!
are already implemented, we may write the Scala type
\begin{lstlisting}
type RWS[R, W, S, A] = ReaderT[WriterT[State[S, *], W, *], R, A] // Equivalent to R => S => (A, W, S)
\end{lstlisting}
A nested transformer is substituted into the \emph{first} argument
of the outer transformer, which has the type constructor kind. We
use the \textsf{``}kind projector\index{kind@\textsf{``}kind projector\textsf{''} plugin}\textsf{''}
plugin for type constructors such as \lstinline!State[S, *]!.

Note that the transformer composition does not necessarily represent
functor composition. For instance, the plain functor composition \lstinline!Reader[R, Writer[W, State[S, A]]]!
is not a monad.

We could stack the monads $K$, $L$, and $M$ in a different order,
e.g., $T_{L}^{T_{M}^{K}}$ or $T_{M}^{T_{K}^{L}}$. In general, different
orders will produce inequivalent monads, although in certain cases
the stacking order does not matter. Table~\ref{tab:Examples-of-monad-stacks}
and the following examples illustrate stacking monads in different
orders.

\begin{table}

\begin{centering}
\begin{tabular}{|c|c|c|c|c|}
\hline 
\textbf{\small{}Base monad $L^{A}$} & \textbf{\small{}Foreign monad $M^{A}$} & \textbf{\small{}Monad $T_{L}^{M}$} & \textbf{\small{}Monad $T_{M}^{L}$} & \textbf{\small{}Same?}\tabularnewline
\hline 
\hline 
{\small{}}\lstinline!Reader[R, A]! & {\small{}}\lstinline!Either[E, A]! & {\small{}$T_{L}^{M,A}=R\rightarrow E+A$} & {\small{}$T_{M}^{L,A}=R\rightarrow E+A$} & {\small{}Yes}\tabularnewline
\hline 
{\small{}}\lstinline!Reader[R, A]! & {\small{}}\lstinline!Writer[W, A]! & {\small{}$T_{L}^{M,A}=R\rightarrow A\times W$} & {\small{}$T_{M}^{L,A}=R\rightarrow A\times W$} & {\small{}Yes}\tabularnewline
\hline 
{\small{}}\lstinline!Reader[R, A]! & {\small{}}\lstinline!List[A]! & {\small{}$T_{L}^{M,A}=R\rightarrow\text{List}^{A}$} & {\small{}$T_{M}^{L,A}\triangleq R\rightarrow\bbnum 1+A\times T_{M}^{L,A}$} & {\small{}No}\tabularnewline
\hline 
{\small{}}\lstinline!Reader[R, A]! & {\small{}}\lstinline!State[S, A]! & {\small{}$T_{L}^{M,A}=R\rightarrow S\rightarrow A\times S$} & {\small{}$T_{M}^{L,A}=S\rightarrow R\rightarrow A\times S$} & {\small{}Yes}\tabularnewline
\hline 
{\small{}}\lstinline!Either[E, A]! & {\small{}}\lstinline!State[S, A]! & {\small{}$T_{L}^{M,A}=S\rightarrow(E+A)\times S$} & {\small{}$T_{M}^{L,A}=S\rightarrow E+A\times S$} & {\small{}No}\tabularnewline
\hline 
{\small{}}\lstinline!Either[E, A]! & {\small{}}\lstinline!Cont[R, A]! & {\small{}$T_{L}^{M,A}=\left(E+A\rightarrow R\right)\rightarrow R$} & {\small{}$T_{M}^{L,A}=\left(A\rightarrow E+R\right)\rightarrow E+R$} & {\small{}No}\tabularnewline
\hline 
\end{tabular}
\par\end{centering}
\caption{\label{tab:Examples-of-monad-stacks}Examples of monads stacked in
different orders.}
\vspace{-0.6\baselineskip}

\end{table}


\subsubsection{Example \label{subsec:Example-reader-state-transformed}\ref{subsec:Example-reader-state-transformed}\index{solved examples}}

Show that $T_{\text{State}}^{\text{Reader}}$ is equivalent to that
of $T_{\text{Reader}}^{\text{State}}$.

\subparagraph{Solution}

The types of the transformers are equivalent: the only difference
is the flipped order of curried arguments. We will verify that the
functions \lstinline!pure! and \lstinline!flatMap! in these transformers
also differ only by the order of curried arguments. Begin by writing
\lstinline!flatMap! for the \lstinline!Reader! and \lstinline!State!
monads:
\begin{align*}
 & \text{flm}_{\text{Reader}}(g^{:A\rightarrow R\rightarrow B})=p^{:R\rightarrow A}\rightarrow r^{:R}\rightarrow(p(r)\triangleright g)(r)\quad,\\
 & \text{flm}_{\text{State}}(g^{:A\rightarrow\text{State}^{S,B}})=p^{:S\rightarrow A\times S}\rightarrow s_{1}^{:S}\rightarrow p(s_{1})\triangleright(a\times s_{2}\rightarrow g(a)(s_{2}))\quad.
\end{align*}
Now we write the code for $T_{\text{Reader}}^{\text{State}}$\textsf{'}s methods:
\begin{align*}
 & T_{\text{Reader}}^{\text{State},A}\triangleq T_{1}^{A}=R\rightarrow S\rightarrow A\times S\quad,\\
 & \text{pu}_{T_{1}}=a^{:A}\rightarrow\_^{:R}\rightarrow\text{pu}_{\text{State}}(a)=a^{:A}\rightarrow\_^{:R}\rightarrow s^{:S}\rightarrow a\times s\quad,\\
 & \text{flm}_{T_{1}}(f^{:A\rightarrow T_{1}^{B}})=t^{:T_{1}^{A}}\rightarrow r^{:R}\rightarrow t(r)\triangleright\text{flm}_{\text{State}}(a^{:A}\rightarrow f(a)(r))\\
 & \quad=t\rightarrow r\rightarrow t(r)\triangleright\big(p^{:\text{State}^{S,A}}\rightarrow s_{1}^{:S}\rightarrow p(s_{1})\triangleright(a\times s_{2}\rightarrow f(a)(r)(s_{2}))\big)\\
 & \quad=t\rightarrow r\rightarrow s_{1}\rightarrow t(r)(s_{1})\triangleright(a\times s_{2}\rightarrow f(a)(r)(s_{2}))\quad.
\end{align*}
The code for $T_{\text{State}}^{\text{Reader}}$ is found by using
Eq.~(\ref{eq:flatmap-for-stateT-transformer}):
\begin{align*}
 & T_{\text{State}}^{\text{Reader},A}\triangleq T_{2}^{A}=S\rightarrow R\rightarrow A\times S\quad,\\
 & \text{pu}_{T_{2}}=a^{:A}\rightarrow s^{:S}\rightarrow\text{pu}_{\text{Reader}}(a\times s)=a^{:A}\rightarrow s^{:S}\rightarrow\_^{:R}\rightarrow a\times s\quad,\\
 & \text{flm}_{T_{2}}(f^{:A\rightarrow T_{2}^{B}})=t^{:T^{A}}\rightarrow s_{1}^{:S}\rightarrow t(s_{1})\triangleright\text{flm}_{\text{Reader}}(a\times s_{2}\rightarrow f(a)(s_{2}))\\
 & \quad=t\rightarrow s_{1}\rightarrow t(s_{1})\triangleright\big(p\rightarrow r\rightarrow(p(r)\triangleright(a\times s_{2}\rightarrow f(a)(s_{2})))(r)\big)\\
 & \quad=t\rightarrow s_{1}\rightarrow r\rightarrow(t(s_{1})(r)\triangleright(a\times s_{2}\rightarrow f(a)(s_{2})))(r)\quad.
\end{align*}
We see that the codes indeed differ only by flipping the curried arguments
$r^{:R}$ and $s_{1}^{:S}$. $\square$

\subsubsection{Example \label{subsec:Example-reader-list-transformed}\ref{subsec:Example-reader-list-transformed}}

Show that the monads $T_{\text{Reader}}^{\text{List}}$ and $T_{\text{List}}^{\text{Reader}}$
are not equivalent.

\subparagraph{Solution}

The difference becomes clear once we write out the types:
\[
T_{\text{Reader}}^{\text{List},A}\triangleq R\rightarrow\text{List}^{A}\quad,\quad\quad T_{\text{List}}^{\text{Reader},A}\triangleq R\rightarrow\bbnum 1+A\times T_{\text{List}}^{\text{Reader},A}\quad.
\]
In a value of type $T_{\text{Reader}}^{\text{List}}$, the injected
dependency (of type $R$) is used to produce an \textsf{``}eager\textsf{''} list.
The length of the resulting list, as well as all its elements, are
computed at once from the injected value of type $R$. In contrast,
a data structure of type $T_{\text{List}}^{\text{Reader}}$ represents
a \textsf{``}lazy\textsf{''} (on-call) sequence: getting the value of each next element
requires calling a function of type $R\rightarrow\bbnum 1+A\times T_{\text{List}}^{\text{Reader}}$
(possibly, a different function each time). The resulting on-call
sequence may be unlimited in length. $\square$

The next example shows that effects of the two monads are not always
independent within the larger transformed monad. An effect of one
monad will sometimes \textsf{``}cancel\textsf{''} an effect of the other.

\subsubsection{Example \label{subsec:Example-either-state-transformed-cancels-effect}\ref{subsec:Example-either-state-transformed-cancels-effect}}

Show that the monads $T_{\text{State}}^{\text{Either}}$ and $T_{\text{Either}}^{\text{State}}$
are not equivalent.

\subparagraph{Solution}

The effect of $\text{State}^{S,A}=S\rightarrow A\times S$ is to produce
an updated internal state (of type $S$) alongside with a result value
of type $A$. Write the types of the transformed monads:
\[
T_{\text{State}}^{\text{Either},A}=S\rightarrow E+A\times S\quad,\quad\quad T_{\text{Either}}^{\text{State},A}=S\rightarrow\left(E+A\right)\times S\quad.
\]
The first type describes a computation that may fail with an error
description (of type $E$) and produce \emph{no} new state, \textsf{``}canceling\textsf{''}
the state-updating effect of the base monad. The second type describes
a computation that never fails to update the state, although it could
fail to give a result of type $A$. We cannot convert a value of type
$T_{\text{State}}^{\text{Either},A}$ (which may fail to update the
state) into a value of type $T_{\text{Either}}^{\text{State},A}$
(which always updates the state).

\paragraph{Transformers for stacks}

The stack $T_{K}^{T_{L}^{M}}$ is a monad whose code is parametric
in $M$. So, we can decide to use it as the monad transformer \emph{for
the monad} $T_{K}^{L}$:
\begin{equation}
T_{T_{K}^{L}}^{M}\triangleq T_{K}^{T_{L}^{M}}\quad.\label{eq:monad-transformers-associativity-of-combination}
\end{equation}
To combine $T_{K}^{T_{L}^{M}}$ with a new monad $N$, we write the
stack $T_{K}^{T_{L}^{T_{M}^{N}}}$ (where $T_{M}$ is $M$\textsf{'}s transformer).
With this technique, we may combine any number of monads in a monad
stack, as long as the transformers for all monads are known (except
for the last one).

Monad stacking can be viewed as a binary operation (which we denote
by $\varangle$) that combines monads $K$ and $L$ into a new monad
$K\varangle L\triangleq T_{K}^{L}$. This operation is associative
\emph{by definition}: the transformer for the monad $T_{K}^{L}$ is
defined via Eq.~(\ref{eq:monad-transformers-associativity-of-combination}),
which we can rewrite as the equation
\[
\left(K\varangle L\right)\varangle M\triangleq K\varangle\left(L\varangle M\right)\quad.
\]
 A monad stack is then denoted unambiguously by, e.g., $K\varangle L\varangle M\varangle N$,
without need for parentheses.

\subsubsection{Example \label{subsec:Example-monad-stack}\ref{subsec:Example-monad-stack}\index{solved examples}}

Define type constructors for the given monad stacks and for their
transformers:

\textbf{(a)} \lstinline!State[S, *]!$\varangle$\lstinline!Eval!

\textbf{(b)} \lstinline!List!$\varangle$\lstinline!Option!$\varangle$\lstinline!Try!

\subparagraph{Solution}

\textbf{(a)} To define the type constructor for \lstinline!State[S, *]!$\varangle$\lstinline!Eval!,
set $M=\text{Eval}$ in the formula for \lstinline!State! monad\textsf{'}s
transformer:
\[
T_{\text{State}}^{M,A}=S\rightarrow M^{A\times S}=S\rightarrow\text{Eval}^{A\times S}\quad.
\]
Now translate the type notation into code, assuming that the type
\lstinline!S! is defined previously:
\begin{lstlisting}
type StateEval[A] = S => Either[(A, S), Unit => (A, S)]
\end{lstlisting}

The transformer for this monad is denoted by \lstinline!State[S, *]!$\varangle$\lstinline!Eval!$\varangle M$,
where $M$ is an arbitrary foreign monad. By definition, 
\[
\text{State}^{S,\bullet}\varangle\text{Eval}^{\bullet}\varangle M^{\bullet}\triangleq\text{State}^{S,\bullet}\varangle\big(\text{Eval}^{\bullet}\varangle M^{\bullet}\big)\quad,
\]
so we need to start with the monad stack \lstinline!Eval!$\varangle M$:
\begin{lstlisting}
type EvalM[A] = M[Either[A, Unit => M[A]]
\end{lstlisting}
Now we apply \lstinline!State!\textsf{'}s transformer to the foreign monad
\lstinline!EvalM! and find:
\begin{lstlisting}
type StateEvalT[M[_], A] = S => M[Either[(A, S), Unit => M[(A, S)]]
\end{lstlisting}
This type constructor is the monad transformer of the monad $\text{State}^{S}\varangle\text{Eval}$.

\textbf{(b)} The stack \lstinline!List!$\varangle$\lstinline!Option!$\varangle$\lstinline!Try!
is defined as the \lstinline!List! monad\textsf{'}s transformer applied to
the stack \lstinline!Option!$\varangle$\lstinline!Try!. So, we
first define the type constructor for \lstinline!Option!$\varangle$\lstinline!Try!,
which is a functor composition:
\begin{lstlisting}
type OptionTry[A] = Try[Option[A]]
\end{lstlisting}
We now apply \lstinline!ListT! to the monad \lstinline!OptionTry!:
\begin{lstlisting}
final case class ListOptionTry[A](value: Try[Option[Option[(A, ListOptionTry[A])]]])
\end{lstlisting}

To define the transformer for the monad \lstinline!ListOptionTry!,
we need to start with the innermost nested monad (\lstinline!Try!)
and apply its transformer (\lstinline!TryT!) to the foreign monad
$M$:
\begin{lstlisting}
type TryM[A] = M[Try[A]]
\end{lstlisting}
The next step is to apply \lstinline!Option!\textsf{'}s transformer to the
monad \lstinline!TryM!:
\begin{lstlisting}
type OptionTryM[A] = M[Try[Option[A]]
\end{lstlisting}
Finally, we apply the \lstinline!ListT! transformer to the last monad:
\begin{lstlisting}
final case class ListOptionTryT[M[_], A](value: M[Try[Option[Option[(A, ListOptionTryT[M, A])]]]])
\end{lstlisting}
$\square$

Does the stacking operation ($\varangle$) have a unit? We notice
from Table~\ref{tab:Known-monad-transformers} that each transformer
$T_{L}^{M}$ somehow mixes the foreign monad $M$ with the type of
the base monad $L$. In every example, if we set $M$ to the identity
monad $\text{Id}$ (defined by $\text{Id}^{A}\triangleq A$), the
transformed type will become equivalent to the base monad $L$. So,
we may expect that property to hold for every transformer:
\[
T_{L}^{\text{Id}}\cong L\quad,\quad\text{equivalently written as:}\quad\quad L\varangle\text{Id}\cong L\quad.
\]
Intuitively, the identity monad has a \textsf{``}trivial effect\textsf{''}. Combining
a trivial effect with another monad should not change that monad\textsf{'}s
effects. So, it is also natural to \emph{define} the monad transformer
for the identity monad as equal to the foreign monad:
\[
T_{\text{Id}}^{M}\triangleq M\quad,\quad\text{equivalently written as:}\quad\quad\text{Id}\varangle M\triangleq M\quad.
\]

Due to these properties of the identity monad, the base monad $L$
can be recovered as $T_{L}^{\text{Id}}$ if we know the code for the
transformer $T_{L}^{M}$. So, if we already have an implementation
for a monad $L$\textsf{'}s transformer $T_{L}$, we do not need to define
the monad $L$\textsf{'}s type and methods separately. This saves time when
implementing monad code in libraries (but may decrease performance).

With these definitions, we find that the monad stacking operation
($\varangle$) resembles the binary operation of a monoid: it is associative
and has a unit (the monad \lstinline!Id!). However, the monad $L\varangle M$
is defined only if the monad $L$ has a transformer. It is unknown\footnote{For a discussion, see \texttt{\href{https://stackoverflow.com/questions/24515876/}{https://stackoverflow.com/questions/24515876/}}}
whether a transformer exists for every monad relevant to functional
programming. The question is open (Problem~\ref{par:Problem-monads-2})
even if restricted to monads whose methods are implemented by fully
parametric code.

Monad transformers certainly cannot exist for monads defined using
code that executes side effects. Examples of that kind are the \lstinline!Future!
monad and other \textsf{``}task-like\textsf{''} monads that perform side effects with
parallel threads. Transformers also cannot exist for external side-effect
monads, such as \lstinline!IO! from the \lstinline!cats-effect!
library or \lstinline!ZIO! from the \lstinline!zio! library. A transformer
must allow a foreign monad to cancel the effects of the base monad,
as we have seen in Example~\ref{subsec:Example-either-state-transformed-cancels-effect}.
However, side effects cannot be undone once they are performed, because
side effects may change the state of the external world irreversibly.\footnote{For a discussion, see \texttt{\href{https://stackoverflow.com/questions/11792275/}{https://stackoverflow.com/questions/11792275/}}} 

Throughout this chapter, we will build transformers for every exponential-polynomial
monad considered in this book (although some transformers will only
partially satisfy the required laws).

\subsection{The monad transformer typeclass}

Transformers such as \lstinline!EitherT! and \lstinline!StateT!
are type constructors that depend on an arbitrary foreign monad $M$
and have the methods \lstinline!flift!, \lstinline!blift!, and \lstinline!frun!
with known type signatures. We may specify these properties via a
typeclass \lstinline!MTrans[T]! that describes what is requred for
$T$ to be a monad transformer. A simple definition of the monad transformer
typeclass can look like this:
\begin{lstlisting}[mathescape=true]
type Id[A] = A        // The identity monad$\color{dkgreen}\texttt{'}$s typeclass instance must be defined elsewhere.
trait MTrans[T[_[_]]] {    // The type parameter T is a type constructor with 2 parameters.
  def monadT[M[_]: Monad]: Monad[T[M, *]]       // A monad instance must exist for T[M, *].
  def flift[M[_]: Monad, A]: M[A] => T[M, A]
  def blift[M[_]: Monad, A]: Base[A] => T[M, A] = frun[Id, M, A](Monad[M].pure)
  def frun[M[_]: Monad, N[_]: Monad, A](phi: M[A] => N[A]): T[M, A] => T[N, A]
}
\end{lstlisting}
The transformer\textsf{'}s code is parametric in the foreign monad $M$ (but
not in the base monad $L$). Although \lstinline!blift! can be implemented
via \lstinline!frun! as $\text{blift}_{L}^{M}\triangleq\text{frun}_{L}^{\text{Id},M}(\text{pu}_{M})$,
it is convenient to keep all three methods defined separately in the
typeclass.

Here is a schematic example of defining a typeclass instance for \lstinline!ReaderT!:
\begin{lstlisting}
final case class Reader[A](run: R => A)     // The fixed type R must be already defined.
final case class ReaderT[M[_], A](run: Reader[M[A]])
implicit val mTransReaderT = new MTrans[ReaderT] {
  def monadT[M[_] : Monad]: Monad[ReaderT[M, *]] = ...
  def flift[M[_] : Monad, A]: M[A] => ReaderT[M, A] = { ma => ReaderT(Reader(_ => ma)) }
  def frun[M[_] : Monad, N[_] : Monad, A](phi: M[A] => N[A]): ReaderT[M, A] => ReaderT[N, A] =
    t => ReaderT(Reader(r => phi(t.run.run(r))))
}
\end{lstlisting}


\subsection{Lifts and runners for monad stacks}

Working with a monad stack, such as $K\varangle L\varangle M\varangle N$,
requires using the effects of all the monads $K$, $L$, $M$, $N$.
The code should appear to be able to compose any combination of Kleisli
functions, e.g.:
\[
p^{:A\rightarrow(K\varangle L\varangle M\varangle N)^{F}}\triangleq f_{1}^{:A\rightarrow L^{B}}\diamond f_{2}^{:B\rightarrow N^{C}}\diamond f_{3}^{:C\rightarrow(L\varangle M)^{D}}\diamond f_{4}^{:D\rightarrow(K\varangle L)^{E}}\diamond f_{5}^{:E\rightarrow K^{F}}\quad,
\]
where the \textsf{``}universal\textsf{''} composition operation $\diamond$ should
somehow apply to Kleisli functions involving any of the given monads
or sub-stacks. We also expect to be able to run the effects of any
one of the monads while keeping the effects of others. To achieve
all that, we need to define the lifts and the runners for the monad
stack.

\paragraph{Lifts}

Any monad contained in a stack, such as $K^{A}$, $L^{A}$, $M^{A}$,
$N^{A}$, $(K\varangle L)^{A}$, $(L\varangle M)^{A}$, etc., can
be lifted to the stack type $(K\varangle L\varangle M\varangle N)^{A}$
by some combination of lifts. Assume that we have the base lifts,
foreign lifts, and the runners of the relevant transformers, such
as:
\[
\text{flift}_{K}^{P}:P\leadsto(K\varangle P)\quad,\quad\text{blift}_{L}^{P}:L\leadsto(L\varangle P)\quad,\quad\text{frun}_{M}^{P,Q}(f^{:P\leadsto Q}):M\varangle P\leadsto M\varangle Q\quad,\quad\text{etc.,}
\]
for any monad $P$. Keep in mind that the transformer for $K\varangle L$
is defined by stacking the transformers for $K$ and $L$. As an example,
let us compute the lifts $P\leadsto K\varangle L\varangle P$ and
$L\varangle M\leadsto L\varangle M\varangle P$: 
\[
\text{flift}_{K\varangle L}^{P}:P\leadsto K\varangle L\varangle P=\text{flift}_{L}^{P}\bef\text{flift}_{K}^{L\varangle P}\quad,\quad\text{blift}_{L\varangle M}^{P}:L\varangle M\leadsto L\varangle M\varangle P=\text{frun}_{L}^{M,M\varangle P}(\text{blift}_{M}^{P})\quad.
\]

Lifting a monad value from a given monad from the middle of the stack
into the full monad stack can require composing several lifts. For
example, consider the task of lifting a value of type $M^{A}$ to
the stack $(K\varangle L\varangle M\varangle N)^{A}$. We may first
lift $M^{A}$ to $(M\varangle N)^{A}$ using $\text{blift}_{M}^{N}$,
then lift the result to $(L\varangle M\varangle N)^{A}$ using $\text{flift}_{L}^{M\varangle N}$,
and finally lift the last result to $(K\varangle L\varangle M\varangle N)^{A}$
via $\text{flift}_{K}^{L\varangle M\varangle N}$. So, we obtain the
following function composition:
\[
\big(\text{blift}_{M}^{N}\bef\text{flift}_{L}^{M\varangle N}\bef\text{flift}_{K}^{L\varangle M\varangle N}\big):M^{A}\rightarrow(K\varangle L\varangle M\varangle N)^{A}\quad.
\]
Equivalently, we may first lift $M^{A}$ to $(L\varangle M)^{A}$
via $\text{flift}_{L}^{M}$, then lift to $(K\varangle L\varangle M)^{A}$
via $\text{flift}_{K}^{L\varangle M}$, and finally use $\text{blift}_{K\varangle L\varangle M}^{N}$,
which is defined as
\[
\text{blift}_{K\varangle L\varangle M}^{N}:K\varangle L\varangle M\leadsto K\varangle L\varangle M\varangle N\triangleq\text{frun}_{K}^{L\varangle M,L\varangle M\varangle N}(\text{frun}_{L}^{M,M\varangle N}(\text{blift}_{M}^{N}))\quad.
\]
With these techniques, we can construct all required liftings in any
monad stack, as long as every monad transformer in the stack has the
methods \lstinline!flift!, \lstinline!blift!, and \lstinline!frun!.

Transformers for certain monads (e.g., the continuation and the \index{monads!codensity monad}codensity
monads) have neither the \lstinline!frun! nor the \lstinline!blift!
methods. Also, task-like monads (such as \lstinline!Future!) and
the external side-effect monads (such as \lstinline!IO! and \lstinline!ZIO!)
have no transformers at all. Values of those monads can be lifted
to a monad stack only when the problematic monad is located at the
deep end of the stack, so that its transformer is not needed. For
example, the monad $N$ at the end of the stack $K\varangle L\varangle M\varangle N$
can be lifted to the stack without need for $N$\textsf{'}s transformer:
\[
\text{flift}_{K\varangle L\varangle M}^{N}:N^{A}\rightarrow(K\varangle L\varangle M\varangle N)^{A}\triangleq\text{flift}_{M}^{N}\bef\text{flift}_{L}^{M\varangle N}\bef\text{flift}_{K}^{L\varangle M\varangle N}\quad.
\]
For this reason, the external side-effect monads and the task-like
monads are usually placed at the deep end of the stack. This workaround
limits the use of those monads in stacks; for instance, a stack cannot
contain both an \lstinline!IO! and a \lstinline!Future! monad. To
provide adequate functionality for applications, the \lstinline!IO!
and \lstinline!ZIO! monads include special methods for running concurrent
computations on multiple threads, which makes it unnecessary to add
a task-like monad to the same monad stack.

While we solved the lifting problem in principle for most monad stacks,
it is impractical for the programmer to have to write manually a composition
of several lifts for every source line in a functor block. Even if
we implement all the lift functions as extension methods and abbreviate
the type annotations as much as possible, the code would have to be
written similarly to the fragment shown

\begin{wrapfigure}{l}{0.408\columnwidth}%
\vspace{-0.9\baselineskip}
\begin{lstlisting}[mathescape=true]
for {    // Using a stack $\color{dkgreen} K\varangle L\varangle M\varangle N$.
  x <- valueM.blift[N].flift[L].flift[K]
  y <- valueK.blift[TL[TM[N]]]
  z <- valueL.blift[TM[N]].flift[K]
} yield ...
\end{lstlisting}
\vspace{-1.25\baselineskip}
\end{wrapfigure}%

\noindent at left. If a monad stack $K\varangle L\varangle M\varangle N$
needs to be changed to $M\varangle L\varangle N\varangle K\varangle P$
because of new program requirements, all source lines in all functor
blocks will have to be modified to accommodate the required changes
in the lifts. Productive practical use of deep monad stacks needs
better techniques. One such technique, the \textsf{``}lift relation\textsf{''}, is
described in Section~\ref{subsec:Constructing-lifts-via-type-relations}.
Another technique is an \textsf{``}MTL-style\textsf{''} monad stack (Section~\ref{subsec:Combining-monads-via-mtl-style}).
Both techniques are based on creating special typeclasses that produce
the required lifts automatically.

\paragraph{Runners}

Having computed a value of type, say, $(K\varangle L\varangle M\varangle N)^{A}$,
we may want to run the effects of a chosen monad (say $M$) using
a known runner $\theta_{M}:M^{A}\rightarrow A$ but keep the effects
of other monads in the stack. If all the monad transformers in the
stack support the foreign and base runners, we can run the effects
of any chosen monad, e.g., like this:
\[
\text{frun}_{K}^{L\varangle M\varangle N}(\text{frun}_{L}^{M\varangle N}(\text{brun}_{M}^{N}(\theta_{M}))):K\varangle L\varangle M\varangle N\leadsto K\varangle L\varangle N\quad.
\]
As in the case of lifts, the implementations of the runners depend
on the order of monads in the stack and will have to be changed if
the stack changes. It does not seem possible to define a \textsf{``}stack
runner\textsf{''} parametric in the chosen monad, allowing the programmer
simply to indicate which monad\textsf{'}s effects need to be run. To see why,
consider a monad stack of type \lstinline!EitherT[E, ReaderT[R, Option, *], A]!.
If we wish to run the effects of the \lstinline!Reader! monad alone,
the result type must be \lstinline!EitherT[E, Option, A]!. But there
is no simple way of obtaining that result type from the type of the
stack: the type \lstinline!EitherT[E, Option, A]! cannot be expressed
as a type constructor \lstinline!Q[Reader, ...]! where \lstinline!Reader!
is just one of the type parameters. This is because the type of the
stack is not parametric in the type of the base monad.

As we will see in this chapter, some monad transformers do not support
base runners at all. Monad stacks containing such transformers are
still usable, but their effects will have to be run in a specific
order, so that the missing base runners are not needed.

\subsection{Constructing lifts via type relations\label{subsec:Constructing-lifts-via-type-relations}}

The \index{monad transformers!lift@\textsf{``}lift relation\textsf{''} technique}\textsf{``}lift
relation\textsf{''} technique creates a type relation that describes all the
possible liftings within a given monad stack. Two monads $P$ and
$Q$ are \textbf{in a lift relation} if there exists a monad morphism
$P\leadsto Q$. If $Q$ is itself a monad stack containing the monad
$P$, we can implement the lift relation $P\leadsto Q$ by using the
monad transformers from that stack. For instance, the monads $L$
and $K\varangle L\varangle M$ are in a lift relation because we can
construct a monad morphism $L\leadsto K\varangle L\varangle M$ as
\[
\big(\text{blift}_{L}^{M}\bef\text{flift}_{K}^{L\varangle M}\big):L\leadsto K\varangle L\varangle M\quad.
\]
At the same time, the monads $M$ and $K\varangle L$ will \emph{not}
be in a lift relation since, in general, we have no way of lifting
the effects of the monad $M$ into the monad $K\varangle L$ (assuming
that we have no monad morphisms $M\leadsto K$ or $M\leadsto L$).

The lift relation is implemented as a type relation \lstinline!MM[P, Q]!
for the monads\textsf{'} type constructors (\lstinline!P!, \lstinline!Q!).
A value of type \lstinline!MM[P, Q]! will contain the required monad
morphism between \lstinline!P! and \lstinline!Q!:
\begin{lstlisting}
trait MM[P[_], Q[_]] { def up[A]: P[A] => Q[A] } // This function must be a monad morphism.
\end{lstlisting}
We define the lift relation recursively. Any monad is always in a
lift relation with itself:
\begin{lstlisting}
implicit def liftableId[P[_]]: MM[P, P] = new MM[P, P] { def up[A] = identity }
\end{lstlisting}
A stack $L\varangle M$ has two lifts, $L\leadsto L\varangle M$ and
$M\leadsto L\varangle M$. A relation instance for the foreign lift
is
\begin{lstlisting}
implicit def foreignMonadToTransformer[KT[_[_], _], M[_] : Monad]
  (implicit kt: MTrans[KT]): MM[M, KT[M, *]] = new MM[M, KT[M, *]] {
    override def apply[A]: M[A] => KT[M, A] = kt.flift[M, A]
}
\end{lstlisting}
It requires more work to define a relation instance for the base lift,
because the type constructor for the base monad cannot be automatically
derived from the transformer\textsf{'}s type. To make the base monad known
to the Scala compiler, we define another type relation that designates
base monads of monad transformers:
\begin{lstlisting}
final case class BaseMonad[L[_], KT[_[_], _]](iso: MM[L, KT[Id, *]])
\end{lstlisting}
It is assumed that the function \lstinline!iso! should be a monad
isomorphism. Declaring a relation instance of \lstinline!BaseMonad!
looks like this example:
\begin{lstlisting}
implicit val readerBase: BaseMonad[Reader, ReaderT] = BaseMonad(new MM[Reader, ReaderT[Id, *]] {
    def apply[A]: Reader[A] => ReaderT[Id, A] = ReaderT[Id, A](_)
})
\end{lstlisting}
Now we can implement a relation instance for the base lift:
\begin{lstlisting}
implicit def baseMonadToTransformer[KT[_[_], _], M[_] : Monad, L[_] : Monad]
  (implicit kt: MTrans[KT], isBase: BaseMonad[L, KT]): MM[L, KT[M, *]] = new MM[L, KT[M, *]] {
    override def apply[A]: L[A] => KT[M, A] = isBase.iso.apply andThen kt.blift[M, A]
}
\end{lstlisting}
The typeclass constraint \lstinline!BaseMonad[L, KT]! permits the
Scala compiler to direct the search for implicits towards finding
the base monad of a given transformer.

Finally, given a stack $K\varangle M$ and a monad $L$, we may lift
$L\leadsto K\varangle M$ if there is already a lift $L\leadsto K$:
\begin{lstlisting}
implicit def monadToTransformer[KT[_[_], _], L[_] : Monad, M[_] : Monad]
  (implicit kt: MTrans[KT], lm: MM[L, M]): MM[L, KT[M, *]] = new MM[L, KT[M, *]] {
    override def apply[A]: L[A] => KT[M, A] = lm.apply andThen kt.flift
  }
\end{lstlisting}
This relation instance needs to have lower priority than the foreign
and base liftings: the Scala compiler should look for simpler liftings
before trying to find a relation instance recursively.

With appropriate syntax definitions and typeclass instances, we may
now write code like this:
\begin{lstlisting}
type Stack3[A] = EitherT[ReaderT[Option, *], A]            // A stack having 3 monads.
implicit val mTrEitherT: MTrans[EitherT] = ...
implicit val baseEither: BaseMonad[Either[E, *], EitherT] = ...
implicit val mTrReaderT: MTrans[ReaderT] = ...
implicit val baseReader: BaseMonad[Reader, ReaderT] = ...
def toEither(x: Int, r: Int): Either[E, Int] = ...

val resultStack3: Stack3[Int] = for { // Lift each value to Stack3 with a single `up`. 
  x <- Option(5).up[Stack3]
  r <- Reader(identity).up[Stack3]
  t <- toEither(x, r).up[Stack3]
} yield t
\end{lstlisting}

To implement the automatic lifts in this way, the programmer needs
to create three implicit values for each monad: a \lstinline!Monad!
typeclass instance, a monad transformer (\lstinline!MTrans!) typeclass
instance, and an instance of the \lstinline!BaseMonad! type relation.
(So, the length of code is linear in the number of supported monad
types.) Those instances can be defined as implicit values in a monad
transformer library. Then the user may declare an arbitrary monad
stack \lstinline!MyStack! and use the \lstinline!up[MyStack]! method
as an automatic lift from any level in the stack.

\subsection{Constructing lifts via typeclasses for monad operations (\textsf{``}MTL-style\textsf{''})\label{subsec:Combining-monads-via-mtl-style}}

The MTL-style\footnote{The name MTL stands for \textsf{``}monad transformer library\textsf{''}.}
monadic\index{monadic program!MTL-style} programming is another way
of achieving automatic lifting of monadic values in arbitrary monad
stacks. The MTL approach has two main ingredients:
\begin{itemize}
\item For a chosen set of \textsf{``}standard\textsf{''} monads (such as the \lstinline!Reader!
monad of type $\text{Reader}^{R,A}\triangleq R\rightarrow A$, the
\lstinline!State! monad of type $\text{State}^{S,A}\triangleq S\rightarrow A\times S$,
etc.), define some typeclasses (\lstinline!ReaderMonadOps!, \lstinline!StateMonadOps!,
etc.) encapsulating all the \textsf{``}effectful operations\textsf{''} specific to
each monad. Refactor all monadic code to use only the operations from
the provided typeclasses. 
\item Provide appropriate typeclass instances for all monad transformers
and all their combinations. For instance, all monad stacks that contain
the \lstinline!State! monad will need to have a \lstinline!StateMonadOps!
typeclass instance. After that, all code written using \lstinline!StateMonadOps!\textsf{'}s
methods will automatically work under any monad stack that contains
the \lstinline!State! monad. 
\end{itemize}
First, we need to define the \textsf{``}effectful operations\textsf{''} corresponding
to each monad. As an example, consider the \lstinline!State! monad
($\text{State}^{S,A}$). Its effect is to manipulate an internal state
value (of type $S$): the state can be read, updated, and automatically
passed on to the next computation. We may define the functions \lstinline!get!
and \lstinline!set! that work with the internal state:
\[
\text{get}:\text{State}^{S,S}\quad,\quad\quad\text{get}\triangleq s^{:S}\rightarrow s\times s\quad,\quad\quad\text{set}:S\rightarrow\text{State}^{S,\bbnum 1}\quad,\quad\quad\text{set}\triangleq s^{:S}\rightarrow\_^{:S}\rightarrow1\times s\quad.
\]

\begin{wrapfigure}{l}{0.43\columnwidth}%
\vspace{-1\baselineskip}

\begin{lstlisting}
val program: State[S, A] = for {
  s1 <- get    // Get the initial state.
  s2  = f(s1)  // Do some computations.
  _ <- set(s2) // Assign the new state.
} yield g(s2)  // Compute a result value.
\end{lstlisting}
\vspace{-0.8\baselineskip}
\end{wrapfigure}%

A \lstinline!State!-monadic program can then be written as shown
at left, without referring to the type signature $S\rightarrow A\times S$.
The two functions \lstinline!get! and \lstinline!set! appear to
be sufficient to manipulate the internal state in an arbitrary way.
So, we regard these two functions as the \textsf{``}effectful operations\index{monads!effectful operations}\textsf{''}
of the \lstinline!State! monad. Any \lstinline!State!-monadic program
may be expressed via these two operations (together with the standard
monad methods \lstinline!map!, \lstinline!flatMap!, and \lstinline!pure!).
To see this formally, consider an arbitrary monadic program $q:\text{State}^{S,A}$
and define functions $f_{1}$ and $f_{2}$ by
\[
f_{1}:S\rightarrow A\triangleq q\bef\pi_{1}\quad,\quad\quad f_{2}:S\rightarrow S\triangleq q\bef\pi_{2}\quad.
\]
These two functions compute the result value and update the state.
Now we can express $q$ equivalently as a monadic program involving
only \lstinline!map!, \lstinline!flatMap!, and the operations \lstinline!get!
and \lstinline!set!:

\begin{wrapfigure}{l}{0.35\columnwidth}%
\vspace{-0.6\baselineskip}

\begin{lstlisting}
q == for {
  s1 <- get
  s2 = f2(s1)
  _ <- set(s2)
} yield f1(s1)
\end{lstlisting}
\vspace{0.4\baselineskip}
\end{wrapfigure}%

~\vspace{-0.9\baselineskip}
\[
q=\text{get}\triangleright\text{flm}_{\text{State}}\big(s_{1}\rightarrow f_{2}(s_{1})\triangleright\text{set}\triangleright(\_\rightarrow f_{1}(s_{1}))^{\uparrow\text{State}}\big)\quad.
\]

We may refactor any \lstinline!State!-monadic code so that it does
not directly refer to the type $S\rightarrow A\times S$ of the \lstinline!State!
monad but instead only uses the operations \lstinline!get! and \lstinline!set!.
For instance, the refactored code will not apply a monadic value to
an argument of type $S$.

Another example is the \lstinline!Either! monad, for which we define
an operation called \lstinline!raise!:
\[
\text{raise}:E\rightarrow E+A\quad,\quad\quad\text{raise}\triangleq e^{:E}\rightarrow e+\bbnum 0^{:A}\quad.
\]
Any \lstinline!Either!-monadic program is a value of type $E+A$
and can always be expressed through \lstinline!raise! and \lstinline!pure!.
We may then refactor any monadic code so that it uses only the \lstinline!raise!
operation but does not refer to the type $E+A$ of the \lstinline!Either!
monad. For instance, the refactored code will not apply pattern matching
directly to monad values.

The second ingredient of the MTL-style programming involves \textsf{``}lifting\textsf{''}
the monad operations to arbitrary monad stacks. For example, consider
the \lstinline!State! monad with the operations $\text{get}:\text{State}^{S,S}$
and $\text{set}:S\rightarrow\text{State}^{S,\bbnum 1}$. For any monad
stack $P$ containing the monad $\text{State}^{S,\bullet}$, we need
to define the \textsf{``}lifted\textsf{''} operations $\text{get}_{P}:P^{S}$ and
$\text{set}_{P}:S\rightarrow P^{\bbnum 1}$. By assumption, $P$ contains
$\text{State}{}^{S,\bullet}$, so a certain composition of lift functions
will give a monad morphism $p:\text{State}^{S,\bullet}\leadsto P^{\bullet}$.
Once $p$ is known, the new operations $\text{get}_{P}$ and $\text{set}_{P}$
are expressed as
\[
\text{get}_{P}:P^{S}\triangleq\text{get}\triangleright p\quad,\quad\quad\text{set}_{P}:S\rightarrow P^{\bbnum 1}\triangleq\text{set}\bef p\quad.
\]

Similarly, the \lstinline!raise! operation of the \lstinline!Either!
monad can be lifted to any monad stack $P$ that contains the \lstinline!Either!
monad. For any such $P$, there exists a monad morphism $p:E+A\rightarrow P^{A}$,
and the lifted operation ($\text{raise}_{P}$) is defined by
\[
\text{raise}_{P}:P^{A}\quad,\quad\quad\text{raise}_{P}\triangleq\text{raise}\triangleright p\quad.
\]

Lifting operations from a monad to a stack usually requires having
a lift function ($p$) that maps values of the specific monad to the
stack. The lift function $p$ will be different for each monad and
each stack, and we would like to avoid implementing $p$ by hand each
time. In MTL-style programming, this is achieved by refactoring the
code to use special typeclasses that encapsulate the effectful operations
of all the required monads. For the \lstinline!State! monad, the
typeclass \lstinline!StateMonadOps! is defined as
\begin{lstlisting}
trait StateMonadOps[F[_], S] { // `F` is any monad that has `State`-like operations.
  def get: F[S]
  def set: S => F[Unit]
}
\end{lstlisting}
We can now write \lstinline!State!-monadic programs by using the
\lstinline!StateMonadOps! typeclass:
\begin{lstlisting}
val ops = implicitly[StateMonadOps[F, S]] // Must be defined before.
val program: F[A] = for {
  s1 <- ops.get
  s2 = f2(s1)
  _ <- ops.set(s2)
} yield f1(s2)
\end{lstlisting}
This code does \emph{not} assume that the monad \lstinline!F! has
the \lstinline!State! monad\textsf{'}s type signature, \lstinline!S => (A, S)!.
So, it will work unmodified with any monad \lstinline!F! that has
the required typeclass instance. The \lstinline!State! monad itself,
of course, admits an instance of \lstinline!StateMonadOps!:
\begin{lstlisting}
implicit val stateMonadOps: StateMonadOps[State[S, *], S] = new StateMonadOps[State[S, *], S] {
  def get: State[S, S] = State(s => (s, s))
  def set: S => State[S, Unit] = s => State(_ => ((), s)))
}
\end{lstlisting}

For the \lstinline!Either! monad, the typeclass \lstinline!EitherMonadOps!
is defined by
\begin{lstlisting}
trait EitherMonadOps[F[_], E] { // `F` is any monad that has `Either`-like operations.
  def raise[A]: E => F[A]
}
\end{lstlisting}
An instance of this typeclass can be implemented for the \lstinline!Either!
monad:
\begin{lstlisting}
implicit val eitherMonadOps: EitherMonadOps[Either[E, *], E] = new EitherMonadOps[Either[E, *], E] {
  def raise[A]: E => Either[E, A] = e => Left(e)
}
\end{lstlisting}

Once all monadic code is refactored to use the monad operations via
typeclasses, it remains to define the relevant typeclass instances
for monad stacks. After that, the refactored code will work unchanged
under any monad stack; the effectful operations will be lifted automatically
through appropriate typeclass functions. Let us see in more detail
how this works for the \lstinline!State! monad.

The goal is to implement a typeclass instance of \lstinline!StateMonadOps!
for any monad stack containing the \lstinline!State! monad; a typeclass
instance of \lstinline!EitherMonadOps! for any stack containing the
\lstinline!Either! monad; and so on, for other monads. To proceed,
we need a rigorous definition of what it means that a monad stack
$P$ \textsf{``}contains\textsf{''} some monad $L$. Intuitively, the stack $P$ should
have the form $P=M_{1}\varangle M_{2}\varangle...\varangle L\varangle...\varangle M_{k}$
for some monads $M_{1}$, ..., $M_{k}$. We can write a definition
by induction: 
\begin{itemize}
\item Base cases: $P$ contains $L$ when $P=L$ or $P=L\varangle Q$ for
some other monad stack $Q$. (The stack $P=L$ can be seen as a special
case of $P=L\varangle Q$ with $Q=\text{Id}$.) The lift function
($p_{L,P}$) is
\[
p_{L,P}:L\leadsto L\varangle Q\quad,\quad\quad p_{L,P}\triangleq\text{blift}_{L}^{Q}\quad.
\]
\item Inductive step: $P$ contains $L$ when $P=N\varangle Q$, where $N$
is some base monad and $Q$ is another monad stack that contains $L$.
The lift function is
\[
p_{L,P}:L\leadsto N\varangle Q\quad,\quad\quad p_{L,P}\triangleq p_{L,Q}\bef\text{flift}_{N}\quad,
\]
where $p_{L,Q}$ is the lift function for the stack $Q$. (By the
inductive assumption, $p_{L,Q}$ is known.)
\end{itemize}
As an example, we will implement a \lstinline!StateMonadOps! instance
for all monad stacks that contain a \lstinline!State! monad. Begin
with the base cases: The \lstinline!State! monad itself already has
a \lstinline!StateMonadOps! instance. If we have a stack of the form
\lstinline!StateT[Q, S, *]! where \lstinline!Q! is any monad, we
use the base lift of the \lstinline!StateT! transformer to implement
the \lstinline!StateMonadOps! typeclass:
\begin{lstlisting}
implicit def stateTMonadOps[S, Q[_]: Monad] = new StateMonadOps[StateT[Q, S, *], S] {
  def get: StateT[Q, S, S] = StateT(s => Monad[Q].pure((s, s)))
  def set: S => StateT[Q, S, Unit] = s => StateT(_ => Monad[Q].pure(((), s)))
}
\end{lstlisting}

In the inductive step, the stack is of the form \lstinline!OtherT[Q, *]!
where \textsf{``}\lstinline!OtherT!\textsf{''} is a monad transformer for the base
monad $N$. By the inductive assumption, we already have a \lstinline!StateMonadOps!
typeclass instance for the monad \lstinline!Q!. Using the \lstinline!flift!
method of the transformer \lstinline!OtherT!, we write:
\begin{lstlisting}
implicit def otherTMonadOps[OtherT[_[_], _], Q[_], S](implicit val qMonadOps: StateMonadOps[Q, S], otherT: MTrans[OtherT]): StateMonadOps[OtherT[Q, *]] = new StateMonadOps[OtherT[Q, *]] {
  def get: OtherT[Q, S] = otherT.flift(qMonadOps.get)
  def set: S => OtherT[Q, Unit] = qMonadOps.set andThen otherT]].flift
}
\end{lstlisting}

To use the MTL-style monad stacks in practice, one needs a library
(such as \texttt{cats-mtl}\footnote{See \texttt{\href{https://typelevel.org/blog/2018/10/06/intro-to-mtl.html}{https://typelevel.org/blog/2018/10/06/intro-to-mtl.html}}})
that defines typeclasses with sufficiently many operations for each
standard monad, so that any desired monadic program may be expressed
through those operations, without using explicit monad types. The
library should also implement instances of those typeclasses for all
supported monad stacks. 

While the MTL style does provide automatic liftings, some problems
remain. 

The first problem is the lack of general principles for the choice
of effectful operations. We have seen that the operations \lstinline!get!
and \lstinline!set! are sufficient to express any \lstinline!State!-monadic
programs. However, it may not be adequate to write code just with
those two operations. As an example, look at \emph{updating}

\begin{wraptable}{l}{0.6\columnwidth}%
\begin{centering}
\vspace{-0.35\baselineskip}
\begin{tabular}{|>{\centering}m{1.3cm}|>{\centering}m{7cm}|}
\hline 
\textbf{\small{}Monad} & \textbf{\small{}Operations}\tabularnewline
\hline 
\hline 
{\small{}$\text{State}^{S,A}$} & {\small{}$\text{get}:\text{State}^{S,S}$}\\
{\small{}$\text{set}:S\rightarrow\text{State}^{S,\bbnum 1}$}\\
{\small{}$\text{update}:(S\rightarrow S)\rightarrow\text{State}^{S,\bbnum 1}$}\tabularnewline
\hline 
{\small{}$\text{Reader}^{R,A}$} & {\small{}$\text{ask}:\text{Reader}^{R,R}$}\\
{\small{}$\text{local}:R\times\text{Reader}^{R,A}\rightarrow\text{Reader}^{R,A}$}\tabularnewline
\hline 
{\small{}$\text{Either}^{E,A}$} & {\small{}$\text{raise}:E\rightarrow\text{Either}^{E,A}$}\\
{\small{}$\text{handle}:(E\rightarrow\text{Either}^{E,A})\times\text{Either}^{E,A}\rightarrow\text{Either}^{E,A}$}\tabularnewline
\hline 
{\small{}$\text{List}^{A}$} & {\small{}$\text{empty}:\text{List}^{A}$}\\
{\small{}$\text{append}:\text{List}^{A}\times\text{List}^{A}\rightarrow\text{List}^{A}$}\\
{\small{}$\text{filter}:\text{List}^{A}\times(A\rightarrow\bbnum 2)\rightarrow\text{List}^{A}$}\tabularnewline
\hline 
{\small{}$\text{Writer}^{W,A}$} & {\small{}$\text{log}:W\rightarrow\text{Writer}^{W,\bbnum 1}$}\\
{\small{}$\text{collect}:\text{Writer}^{W,A}\rightarrow\text{Writer}^{W,A\times W}$}\\
{\small{}$\text{process}:\text{Writer}^{W,A\times(W\rightarrow W)}\rightarrow\text{Writer}^{W,A}$}\\
{\small{}$\text{clear}:\text{Writer}^{W,A}\rightarrow\text{Writer}^{W,A}$}\tabularnewline
\hline 
{\small{}$\text{Cont}^{R,A}$} & {\small{}$\text{abort}:R\rightarrow\text{Cont}^{R,A}$}\\
{\small{}$\text{callcc}:((A\rightarrow\text{Cont}^{R,B})\rightarrow\text{Cont}^{R,A})\rightarrow\text{Cont}^{R,A}$}\tabularnewline
\hline 
\end{tabular}
\par\end{centering}
\caption{Known operations for some monads.\label{tab:effectful-operations-for-some-monads}}
\vspace{-0.4\baselineskip}
\end{wraptable}%

\noindent the state using a given function of type $S\rightarrow S$.
In many cases, updating is the same as \lstinline!get!ting the current
state value and immediately \lstinline!set!ting a new value. But
suppose that certain state updates must be handled in a special way:
e.g., atomic updates in a concurrent program; updates wrapped in a
database transaction; or updates that must be run on a designated
processing thread (such as the thread that drives the GUI events).
Special handling of updates cannot be implemented through \lstinline!get!
and \lstinline!set!; a new effectful operation (\lstinline!update!)
must be provided to the programmer.

Table~\ref{tab:effectful-operations-for-some-monads} shows a number
of operations for some monads.\footnote{Operations were gathered from the \texttt{cats-mtl} documentation
and the papers \textsf{``}\emph{Monad transformers and modular interpreters}\textsf{''}
(see \texttt{\href{http://web.cecs.pdx.edu/~mpj/pubs/modinterp.html}{http://web.cecs.pdx.edu/$\sim$mpj/pubs/modinterp.html}})
and \textsf{``}\emph{Modular monad transformers}\textsf{''} (see \texttt{\href{https://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.219.5365}{https://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.219.5365}}).} The choice of operations seems to be heuristic and not following
any principle or system. It is not easy to decide what operations
will be useful or necessary in practical tasks involving a given monad.
(Do we need a \lstinline!filter! operation for the \lstinline!Either!
monad?) 

Different libraries choose different sets of supported operations.
However, adding a new operation to a monad in an MTL-style library
means updating all typeclasses related to that monad. Users who cannot
modify the library code will be unable to add new operations.

The second problem is the lack of a general method for lifting effectful
operations to arbitrary monad transformers.\footnote{M.~\index{Mauro Jaskelioff}Jaskelioff developed a technique that
can lift effectful operations systematically to almost all monad stacks;
see the paper \texttt{\href{https://www.fceia.unr.edu.ar/~mauro/pubs/monatron.pdf}{https://www.fceia.unr.edu.ar/$\sim$mauro/pubs/monatron.pdf}}} So far, the examples in this subsection were limited to operations
with type signatures of the form $L^{A}$ or $A\rightarrow L^{B}$.
All operations of this form are lifted from the monad $L$ to a monad
stack $P$ by composing with a lift function $p:L^{A}\rightarrow P^{A}$.
However, some operations have significantly different type signatures
and cannot be lifted to arbitrary monad stacks by composing with a
lift. For instance, an operation called \lstinline!withEnv! (defined
for the \lstinline!Reader! monad) has the type signature $R\rightarrow\text{Reader}^{R,A}\rightarrow\text{Reader}^{R,A}$.
In that type signature, some \lstinline!Reader! values are used as
arguments (that is, in a contravariant position). So, \lstinline!withEnv!
cannot be converted to a function of type $R\rightarrow P^{A}\rightarrow P^{A}$
by composing with a lift function $p:\text{Reader}^{R,A}\rightarrow P^{A}$.
Another example is the \lstinline!Writer! monad\textsf{'}s \lstinline!clear!
operation that has the type $\text{Writer}^{W,A}\rightarrow\text{Writer}^{W,A}$.
Knowing only a lift function $p:\text{Writer}^{W,A}\rightarrow P^{A}$
is not sufficient for transforming \lstinline!clear! into a function
of type $P^{A}\rightarrow P^{A}$.

Lifting \lstinline!clear! to a given monad stack $P$ (say, $P=\,$\lstinline!State!$\varangle$\lstinline!Writer!
or $P=\,$\lstinline!Writer!$\varangle$\lstinline!Cont!) requires
custom code. Let us see how to write that code. For the stack $P=\,$\lstinline!State!$\varangle$\lstinline!Writer!,
we need to implement a function $\text{clear}_{P}$ of type $P^{A}\rightarrow P^{A}$
given a function \lstinline!clear! with type signature
\[
\text{clear}:\text{Writer}^{W,A}\rightarrow\text{Writer}^{W,A}=W\times A\rightarrow W\times A\quad.
\]
Since the stack type is $P^{A}\triangleq T_{\text{State}}^{\text{Writer},A}=S\rightarrow W\times A\times S$,
the code for $\text{clear}_{P}$ is
\[
\text{clear}_{P}:\left(S\rightarrow W\times A\times S\right)\rightarrow S\rightarrow W\times A\times S\quad,\quad\quad\text{clear}_{P}\triangleq p^{:S\rightarrow W\times A\times S}\rightarrow p\bef(\text{clear}\boxtimes\text{id}^{S})\quad.
\]
For the stack $P=\,$\lstinline!Writer!$\varangle$\lstinline!Cont!,
or more verbosely:
\[
P^{A}\triangleq T_{\text{Writer}}^{\text{Cont},A}=(W\times A\rightarrow R)\rightarrow R\quad,
\]
the lifted operation $\text{clear}_{P}$ of type $\left((W\times A\rightarrow R)\rightarrow R\right)\rightarrow(W\times A\rightarrow R)\rightarrow R$
is implemented as
\[
\text{clear}_{P}\triangleq p^{:(W\times A\rightarrow R)\rightarrow R}\rightarrow q^{:W\times A\rightarrow R}\rightarrow p(\text{clear}\bef q)\quad.
\]

These examples show that lifting an operation to a specific monad
transformer will require custom code adapted to every combination
of a monad and an operation. The length of required custom code is
quadratic in the number of supported monads.

The third problem is the large number of typeclass instances that
MTL libraries need to maintain. As we have seen in the example with
\lstinline!StateMonadOps!, just two implicit functions per monad
type are in principle sufficient to define the operation typeclasses
for all monad stacks. This would make the number of typeclass instances
linear in the number of supported monads. However, to make the code
run faster, libraries provide typeclass instances for every combination
of monads (say, \lstinline!Reader! with \lstinline!State!, \lstinline!Either!
with \lstinline!Reader!, and so on). This makes the required number
of typeclass instances quadratic in the number of supported monads.
Adding a new monad to an MTL library requires adding many new typeclass
instances.

For these reasons, MTL libraries usually support only a limited number
of monads and operations.

\section{Laws of monad transformers}

\subsection{Motivation for the laws of lifts}

A monad transformer creates a new monad that combines the effects
of other monads. Our next goal is to derive the properties required
for the new monad to work well in practice. So, let us look at the
programmer\textsf{'}s intuitions about monadic programs written using transformers.

To be specific, assume that we have combined two monads $L$ and $M$
into a transformed monad $T\triangleq L\varangle M\triangleq T_{L}^{M}$
and defined the necessary lifts, $\text{up}_{L}:L^{A}\rightarrow T^{A}$
and $\text{up}_{M}:M^{A}\rightarrow T^{A}$. After these definitions,
a programmer should be able to write functor blocks with lifted values
of $L$ and $M$. 

Programmers will certainly expect all previously accepted properties
of functor blocks to remain valid after lifting all monadic values
of types $L$ and $M$ to the transformed monad $T$. A monadic program
in $T$ could look like this:

\begin{wrapfigure}{l}{0.27\columnwidth}%
\vspace{-0.8\baselineskip}
\begin{lstlisting}
for {
  i <- someValueL.up
  x <- someValueT(i)
  y <- anotherValueT(y)
  z <- someValueM(x).up
} yield z
\end{lstlisting}

\vspace{-1.2\baselineskip}
\end{wrapfigure}%

\noindent This program combines values of $L$ and $M$ lifted to
$T$ with some directly available values of the monad $T$ (say, obtained
from other monadic programs). Refactoring such programs involves,
as a special case, refactoring of functor blocks in the monad $T$
alone. It follows that $T$ must itself satisfy the monad laws, \textemdash{}
the laws we derived in Chapter~\ref{chap:Semimonads-and-monads}
by analyzing various functor block refactorings. 

There are some additional code refactorings specific to lifted monadic
values. Lifted values may occur before or after a source line with
an arbitrary value of $T$. Similarly to the standard monadic refactorings,
we consider three cases: a lifted \lstinline!pure! method before
a source line, a lifted \lstinline!pure! method after a source line,
and refactoring two adjacent lifted source lines into a separate functor
block.

If $L$\textsf{'}s \lstinline!pure! method is used before a source line, we
expect this refactoring to work:

\vspace{-0.6\baselineskip}

\noindent \texttt{\textcolor{blue}{\footnotesize{}}}%
\begin{minipage}[t]{0.48\columnwidth}%
\textcolor{darkgray}{\footnotesize{}}
\begin{lstlisting}
           // Anywhere inside a for/yield:
  y <- Monad[L].pure(x).up // Assume x: A
  z <- f(y)                // f: A => T[B]
\end{lstlisting}
%
\end{minipage}\texttt{\textcolor{blue}{\footnotesize{}\hspace*{\fill} }}%
\begin{minipage}[t]{0.48\columnwidth}%
\texttt{\textcolor{blue}{\footnotesize{}}}
\begin{lstlisting}
// Must be equivalent to...
  y = x     // x: A
  z <- f(y) // f: A => T[B]
\end{lstlisting}
%
\end{minipage}\texttt{\textcolor{blue}{\footnotesize{}\smallskip{}
}}{\footnotesize\par}

The corresponding law is \lstinline!pure(x).up.flatMap(f) == f(x)!
or 
\[
\text{pu}_{L}\bef\text{blift}\bef\text{flm}_{T}(f)=f\quad.
\]

If $L$\textsf{'}s \lstinline!pure! method is used after a source line, we
expect the following code equivalence:

\vspace{-0.5\baselineskip}

\noindent \texttt{\textcolor{blue}{\footnotesize{}}}%
\begin{minipage}[t]{0.48\columnwidth}%
\textcolor{darkgray}{\footnotesize{}}
\begin{lstlisting}
           // Anywhere inside a for/yield:
  x <- t   // Assume t: T[A]
  y <- Monad[L].pure(x).up
\end{lstlisting}
%
\end{minipage}\texttt{\textcolor{blue}{\footnotesize{}\hspace*{\fill} }}%
\begin{minipage}[t]{0.48\columnwidth}%
\texttt{\textcolor{blue}{\footnotesize{}}}
\begin{lstlisting}
 // Must be equivalent to...
  x <- t   // Assume t: T[A]
  y = x
\end{lstlisting}
%
\end{minipage}\texttt{\textcolor{blue}{\footnotesize{}\smallskip{}
}}{\footnotesize\par}

The corresponding law is \lstinline!t.flatMap(x => L.pure(x).up) == t!
or 
\[
\text{flm}_{T}(\text{pu}_{L}\bef\text{blift})=\text{id}\quad.
\]

The third law comes from refactoring a functor block when two adjacent
source lines are lifted from $L$. We may equivalently put these lines
in a functor block in $L$ and then lift its result to $T$:

\vspace{-0.4\baselineskip}

\noindent \texttt{\textcolor{blue}{\footnotesize{}}}%
\begin{minipage}[t]{0.48\columnwidth}%
\textcolor{darkgray}{\footnotesize{}}
\begin{lstlisting}
            // Anywhere inside a for/yield:
  x <- p.up      // Assume p: L[A]
  y <- q(x).up   // q: A => L[B]
\end{lstlisting}
%
\end{minipage}\texttt{\textcolor{blue}{\footnotesize{}\hspace*{\fill} }}%
\begin{minipage}[t]{0.48\columnwidth}%
\texttt{\textcolor{blue}{\footnotesize{}}}
\begin{lstlisting}
 // Must be equivalent to...
  pq = for { x <- p; y <- q(x) } yield y
  y <- pq.up // Lift a refactored block.
\end{lstlisting}
%
\end{minipage}\texttt{\textcolor{blue}{\footnotesize{}\smallskip{}
}}{\footnotesize\par}

The corresponding law is \lstinline!p.up.flatMap(x => q(x).up) == p.flatMap(q).up!
or 
\[
\text{blift}\bef\text{flm}_{T}(q\bef\text{blift})=\text{flm}_{L}(q)\bef\text{blift}\quad.
\]

The form of these three laws can be simplified if we rewrite them
in terms of the Kleisli composition operations $\diamond_{_{L}}$
and $\diamond_{_{T}}$. Recall that \lstinline!flatMap! is related
to the Kleisli composition by
\[
f^{:A\rightarrow T^{B}}\diamond_{_{T}}g^{:B\rightarrow T^{C}}=f\bef\text{flm}_{T}(g)\quad.
\]
The first law is then written as
\[
\text{pu}_{L}\bef\text{blift}\bef\text{flm}_{T}(f)=(\text{pu}_{L}\bef\text{blift})\diamond_{_{T}}f\overset{!}{=}f\quad.
\]
The second law is not of the form $f\bef\text{flm}\left(...\right)$,
so let us pre-compose it with an arbitrary $f^{:A\rightarrow T^{B}}$:
\[
f\bef\text{flm}_{T}(\text{pu}_{L}\bef\text{blift})=f\diamond_{_{T}}(\text{pu}_{L}\bef\text{blift})\overset{!}{=}f\bef\text{id}=f\quad.
\]
Pre-compose also the third law with an arbitrary function $p^{:A\rightarrow L^{B}}$:
\[
p\bef\text{blift}\bef\text{flm}_{T}(q\bef\text{blift})=(p\bef\text{blift})\diamond_{_{T}}(q\bef\text{blift})\overset{!}{=}p\bef\text{flm}_{L}(q)\bef\text{blift}=(p\diamond_{_{L}}q)\bef\text{blift}\quad.
\]

The first two laws are now easier to interpret: they require the function
($\text{pu}_{L}\bef\text{blift}$) to be both a left and a right unit
for the Kleisli composition $\diamond_{_{T}}$. However, the monad
laws of $T$ already provide such a unit, namely $\text{pu}_{T}$.
An associative operation can have only one two-sided unit, so ($\text{pu}_{L}\bef\text{blift}$)
must be equal to $\text{pu}_{T}$. To see that, it is sufficient to
write the equation
\[
(\text{pu}_{L}\bef\text{blift})=(\text{pu}_{L}\bef\text{blift})\diamond_{_{T}}\text{pu}_{T}=\text{pu}_{T}\quad.
\]
So, the first two laws are equivalent to a single\index{identity laws!of monad transformer\textsf{'}s lift}
\textbf{identity law}:
\[
\text{pu}_{L}\bef\text{blift}=\text{pu}_{T}\quad.
\]

The third law says that the post-composition with \lstinline!blift!
will map a Kleisli composition in $L$ to a Kleisli composition in
$T$. This is the \textbf{composition law}\index{composition law!of monad transformer\textsf{'}s lift}
of lifts. This law is sometimes easier to verify when expressed through
\lstinline!flatten!, although the formulation of the law becomes
less visually clear:%
\begin{comment}
precarious formatting
\end{comment}

\begin{wrapfigure}{i}{0.3\columnwidth}%
\begin{centering}
\vspace{-1.65\baselineskip}
\[
\xymatrix{\xyScaleY{1.6pc}\xyScaleX{2.0pc}L^{L^{A}}\ar[d]\sb(0.45){\text{ftn}_{L}}\ar[r]\sb(0.5){\text{blift}} & T^{L^{A}}\ar[r]\sb(0.5){\text{blift}^{\uparrow T}} & T^{T^{A}}\ar[d]\sp(0.45){\text{ftn}_{T}}\\
L^{A}\ar[rr]\sp(0.5){\text{blift}} &  & T^{A}
}
\]
\par\end{centering}
\vspace{0.2\baselineskip}
\end{wrapfigure}%

~\vspace{-0.35\baselineskip}
\[
\text{blift}\bef\text{blift}^{\uparrow T}\bef\text{ftn}_{T}=\text{ftn}_{L}\bef\text{blift}\quad.
\]

\noindent The identity and composition law enforce a certain compatibility
of \lstinline!blift! with the monad methods of $L$ and $T_{L}^{M}$.
Laws of this form were introduced in Section~\ref{subsec:Monads-in-category-theory-monad-morphisms}
where we considered monad morphisms\index{monad morphism} $\phi:M\leadsto N$
between two monads $M$ and $N$. So, we have now shown that the expected
properties of \lstinline!blift! in functor blocks are equivalent
to the requirement that \lstinline!blift! should be a monad morphism
of type $L\leadsto T_{L}^{M}$.

Since we expect to be able to use the monads $L$ and $M$ equally
well within a functor block, the same refactorings must be possible
with values of type $M$ instead of $L$. Thus, the laws of monad
morphisms must hold also for the foreign lift function ($\text{flift}_{L}:M\leadsto T_{L}^{M}$).

Since monad morphisms are natural transformations (Statement~\ref{subsec:Statement-flatMap-formulation-of-monad-morphism}),
both \lstinline!blift! and \lstinline!flift! obey the corresponding
naturality laws. The naturality laws can be also motivated by considering
functor blocks where a source line with a lift occurs next to a non-source
line. We will omit the details, keeping in mind that naturality laws
always hold for fully parametric code.

\subsection{Motivation for the laws of runners}

A monad\textsf{'}s runner ($\theta_{M}:M^{A}\rightarrow A$) extracts results
of type $A$ from monadic values of type $M^{A}$. The use of a runner
will agree with programmer\textsf{'}s intuition if the runner obeys the laws
of monad morphisms (see Definition~\ref{subsec:Definition-monad-morphism});
a runner $\theta_{M}$ must be a monad morphism $M\leadsto\text{Id}$
between $M$ and the identity monad ($\text{Id}$). Heuristically,
a runner \textsf{``}executes\textsf{''} or \textsf{``}runs\textsf{''} the effects of the monad $M$
and delivers an effect-free value as a result.

How can we extract the result values from a monad stack that combines
the effects of several monads? Let us try to create a runner $\theta_{T}:T_{L}^{M,A}\rightarrow A$
for the transformed monad $T_{L}^{M}$ assuming that both $L$ and
$M$ have known runners $\theta_{L}$ and $\theta_{M}$.

As a first example, assume a compositional transformer such as $T_{L}^{M}=L\circ M$;
this is the case for $L=$ \lstinline!Reader! and some other monads.
Given a runner $\theta_{M}$, we may first run $M$\textsf{'}s effects by using
$\theta_{M}^{\uparrow L}$,
\[
\theta_{M}^{\uparrow L}:L^{M^{A}}\rightarrow L^{A}\quad.
\]
A result value of type $A$ can be now extracted by using $L$\textsf{'}s runner.
So, we may express $\theta_{T}$ as
\[
\theta_{T}\triangleq\theta_{M}^{\uparrow L}\bef\theta_{L}\quad.
\]
If we first run the effects of $L$ and then those of $M$, the result
will be the same: $\theta_{L}^{\uparrow L}\bef\theta_{M}=\theta_{M}\bef\theta_{L}$
by the (assumed) naturality of $\theta_{L}$. So, the runners commute.
This is intuitively to be expected because the two runners work on
different effects that are separately present in a value of type $T_{L}^{M}$.

A similar situation occurs for pass/fail monads that have composed-inside
transformers. We may run the effects of only one of the monads, or
both if needed; the runners commute.

Now consider a non-compositional transformer such as \lstinline!StateT!:
\[
T_{\text{State}}^{M,A}=S\rightarrow M^{A\times S}\quad.
\]
In this case, we cannot run the effects of \lstinline!State! using
$\theta_{\text{State}}$ or the effects of $M$ using $\theta_{M}^{\uparrow\text{State}}$:
the types do not match. Compare the types of \lstinline!brun!, \lstinline!frun!,
$\theta_{\text{State}}$, and $\theta_{M}^{\uparrow\text{State}}$:
\begin{align*}
 & \text{brun}:T_{\text{State}}^{M,A}\rightarrow M^{A}=(S\rightarrow M^{A\times S})\rightarrow M^{A}\quad\quad\text{vs.}\quad\theta_{\text{State}}:\left(S\rightarrow A\times S\right)\rightarrow A\quad,\\
 & \text{frun}:T_{\text{State}}^{M,A}\rightarrow\text{State}^{S,A}=(S\rightarrow M^{A\times S})\rightarrow S\rightarrow A\times S\quad\quad\text{vs.}\quad\theta_{M}^{\uparrow\text{State}}:(S\rightarrow M^{A}\times S)\rightarrow S\rightarrow A\times S\quad.
\end{align*}
We need to use new runners specially adapted to \lstinline!StateT!,
as shown in Section~\ref{subsec:Monad-transformers-for-standard-monads}.
The foreign runner (\lstinline!frun!) is a function of $\theta_{M}$
and works for all foreign monads $M$. The base runner \lstinline!brun!,
however, is not a function of $\theta_{\text{State}}$ but has custom
code. So, the commutativity of runners,
\[
\text{frun}_{\text{State}}(\theta_{M})\bef\theta_{\text{State}}(i)\overset{?}{=}\text{brun}_{\text{State}}(i)\bef\theta_{M}\quad,
\]
is no longer automatic and needs to be verified. Apply both sides
to a value $t^{:T_{\text{State}}^{M,A}}$:
\begin{align*}
{\color{greenunder}\text{left-hand side}:}\quad & t\triangleright\text{frun}_{\text{State}}(\theta_{M})\bef\theta_{\text{State}}(i)=t\triangleright(t\rightarrow t\bef\theta_{M})\bef(t\rightarrow i\triangleright t\triangleright\pi_{1})\\
{\color{greenunder}\text{compute composition}:}\quad & \quad=i\triangleright(t\bef\theta_{M})\triangleright\pi_{1}=i\triangleright t\bef\theta_{M}\bef\pi_{1}\quad,\\
{\color{greenunder}\text{left-hand side}:}\quad & t\triangleright\text{brun}_{\text{State}}(i)\bef\theta_{M}=t\triangleright(t\rightarrow i\triangleright t\triangleright\pi_{1}^{\uparrow M})\triangleright\theta_{M}=i\triangleright t\bef\gunderline{\pi_{1}^{\uparrow M}\bef\theta_{M}}\\
{\color{greenunder}\text{naturality law of }\theta_{M}:}\quad & \quad=i\triangleright t\bef\theta_{M}\bef\pi_{1}\quad.
\end{align*}
Both sides are now equal, which proves the commutativity of runners
for \lstinline!StateT!.

These examples motivate the requirement that a monad transformer should
come equipped with a base runner $\text{brun}_{L}:T_{L}^{M}\leadsto M$
and a foreign runner $\text{frun}_{L}(\theta_{M}):T_{L}^{M}\leadsto L$
as long as the monads $L$ and $M$ have runners $\theta_{L}$ and
$\theta_{M}$. The foreign runner must be a function $\theta_{M}$,
but the base runner is not necessarily expressed as a function of
$\theta_{L}$. The effects of the base monad and of the foreign monad
may be run in any order, and the results must be the same:
\[
\text{brun}_{L}\bef\theta_{M}=\text{frun}_{L}(\theta_{M})\bef\theta_{L}\quad.
\]

Some monads $M$ do not admit monad morphisms $M\leadsto\text{Id}$
but instead have useful monad morphisms $M\leadsto N$ with suitable
target monads $N$. A monad morphism $M\leadsto N$ may partially
run the effects of $M$ and represent the results using $N$\textsf{'}s effects.
For instance, the continuation monad can be mapped to a task monad
such as \lstinline!Future!; the \lstinline!Option! monad can be
mapped to an \lstinline!Either! monad. 

When a foreign monad $M$ requires a runner of the form $\phi:M\leadsto N$
with a target monad $N\not\cong\text{Id}$, we would like to be able
to map the monad stacks accordingly as $T_{L}^{M}\leadsto T_{L}^{N}$,
possibly running some of $M$\textsf{'}s effects but keeping $L$\textsf{'}s effects
unchanged. It is natural to expect that the same foreign runner ($\text{frun}_{L}$)
should be able to use $\phi$ instead of $\theta_{M}$. We can then
compute a map $\text{frun}_{L}\left(\phi\right):T_{L}^{M}\leadsto T_{L}^{N}$
that runs the stacks as required.

When the base monad $L$ requires a runner with a target monad $K$,
we will similarly need a monad morphism $T_{L}^{M}\leadsto T_{K}^{M}$
that can partially run the effects of $L$. Since $T_{K}^{M}$ depends
on $K$ non-parametrically, we cannot expect to have a \textsf{``}universal\textsf{''}
base runner that uses $\phi:L\leadsto K$ as a parameter. The extended
base runner $\text{brun}_{L,K}:T_{L}^{M}\leadsto T_{K}^{M}$ will
work for all foreign monads $M$ but needs to have custom code specially
adapted to the monads $L$ and $K$.

The pass/fail monads (such as \lstinline!Option! and \lstinline!Try!)
show one example where a universal base runner\index{monad transformers!universal base runner}
exists. Recall that the monad transformers for pass/fail monads work
by functor composition. If $L^{A}=\bbnum 1+A$ and $K^{A}\triangleq E+A$
(where $E$ is a fixed type representing error information), we can
choose an arbitrary runner $\phi:L\leadsto K$ and compute the universal
base runner as 
\[
\text{brun}_{L,K}(\phi):(T_{L}^{M}\leadsto T_{K}^{M})\triangleq\phi^{\uparrow M}\quad.
\]

Apart from the laws of monad morphisms, do we need additional properties
for the runners? For intuition, recall the example with the continuation
monad\textsf{'}s runner (Section~\ref{subsec:The-continuation-monad}) that
works by first mapping \lstinline!Cont! $\leadsto$ \lstinline!Future!
and then \lstinline!Future! $\leadsto$ \lstinline!Id!. Denote the
two runners by
\[
\phi_{1}:\text{Cont}^{R,A}\rightarrow\text{Future}^{A}\quad,\quad\quad\phi_{2}:\text{Future}^{A}\rightarrow A\quad.
\]
The runner for \lstinline!Cont! is then defined by $\theta_{\text{Cont}}\triangleq\phi_{1}\bef\phi_{2}$.
Now consider how we would run a monad stack $T_{L}^{\text{Cont}}$.
We may use the foreign runner with $\theta_{\text{Cont}}$ as
\[
\text{frun}_{L}(\theta_{\text{Cont}}):T_{L}^{\text{Cont}}\leadsto L\quad.
\]
We could also use those runners to map $T_{L}^{\text{Cont}}\leadsto T_{L}^{\text{Future}}$
and then $T_{L}^{\text{Future}}\leadsto T_{L}^{\text{Id}}\cong L$:
\[
\text{frun}_{L}(\phi_{1}):T_{L}^{\text{Cont}}\leadsto T_{L}^{\text{Future}}\quad,\quad\quad\text{frun}_{L}(\phi_{2}):T_{L}^{\text{Future}}\leadsto L\quad.
\]
Intuitively, we would expect that the composition of these two runners
should be the same as when running $T_{L}^{\text{Cont}}$ directly
into $L$:
\[
\text{frun}_{L}(\phi_{1})\bef\text{frun}_{L}(\phi_{2})\overset{!}{=}\text{frun}_{L}(\theta_{\text{Cont}})=\text{frun}_{L}(\phi_{1}\bef\phi_{2})\quad.
\]
The composition $\phi_{1}\bef\phi_{2}$ of any two monad morphisms
$\phi_{1}$ and $\phi_{2}$ is again a monad morphism (see Statement~\ref{subsec:Statement-monadic-morphism-composition}).
This suggests the \textbf{composition law}\index{composition law!of foreign monad runners}:
\begin{equation}
\text{frun}_{L}(\phi_{1})\bef\text{frun}_{L}(\phi_{2})\overset{!}{=}\text{frun}_{L}(\phi_{1}\bef\phi_{2})\quad.\label{eq:composition-law-of-frun}
\end{equation}
This law is similar to the composition law of \lstinline!map!. By
analogy, we also impose the \textbf{identity law}\index{identity laws!of foreign monad runners}:
\[
\text{frun}_{L}(\text{id}^{:M^{A}\rightarrow M^{A}})\overset{!}{=}\text{id}^{:T_{L}^{M,A}\rightarrow T_{L}^{M,A}}\quad.
\]

Finally, let us consider the usage of a monad stack $T_{L}^{M}$ within
a functor block. Typically, we would lift some values of types $L^{A}$
or $M^{A}$ to the stack; at the end of the computation, we may run
some (or all) of the effects. There are two possssible cases: we lift
a monadic value and then run the effects of the same monad; or we
run the effects of the other monad. 

In the first case, we lift a value $m:M^{A}$ to the stack $T_{L}^{M}$
and then run the effects of $M$ using $\text{frun}_{L}(\theta_{M})$,
getting a value of type $L^{A}$. The result is a transformation
\[
\text{flift}_{L}\bef\text{frun}_{L}(\theta_{M}):M^{A}\rightarrow L^{A}\quad.
\]
Note that both \lstinline!flift! and \lstinline!frun! are monad
morphisms, so their composition is again a monad morphism $M\leadsto L$.
Since $M$ is an arbitrary foreign monad, we cannot expect the monad
$L$ to describe any effects of the foreign monad $M$. So, the result
value of type $L^{A}$ must have an empty $L$-effect, that is, it
must be created from a value $a^{:A}$ via $\text{pu}_{L}$. The only
way to obtain a value $a^{:A}$ is by applying a runner $\theta_{M}$
to the value $m:M^{A}$. So, we derived the \textsf{``}purity\textsf{''} law:
\[
m\triangleright\text{flift}_{L}\triangleright\text{frun}_{L}(\theta_{M})=m\triangleright\theta_{M}\triangleright\text{pu}_{L}\quad,\quad\text{or equivalently:}\quad\quad\text{flift}_{L}\bef\text{frun}_{L}(\theta_{M})=\theta_{M}\bef\text{pu}_{L}\quad.
\]

The analogous purity law\index{purity laws!of monad transformer runners}
for \lstinline!blift! and \lstinline!brun! is
\[
\text{blift}\bef\text{brun}=\theta_{L}\bef\text{pu}_{M}\quad.
\]

In the second case, we lift a foreign value $m:M^{A}$ to the stack,
obtaining a value $t\triangleq\text{flift}\left(m\right)$, and then
apply the \emph{base} runner to $t$ (running just the effects of
$L$). This yields a monad morphism $M^{A}\rightarrow M^{A}$. We
expect this morphism to be an identity function\footnote{Is there a non-identity monad morphism of type $M^{A}\rightarrow M^{A}$
that is parametric in the monad $M$? See Problem~\ref{par:Problem-identity-natural-monad-morphism}.} because the monad $M$ is arbitrary, and the code of \lstinline!flift!
and \lstinline!brun! must be parametric in $M$. This requirement
is written as the law
\[
m\triangleright\text{flift}\triangleright\text{brun}\overset{!}{=}m\quad,\quad\text{or equivalently:}\quad\quad\text{flift}\bef\text{brun}\overset{!}{=}\text{id}\quad,
\]
called the \textbf{non-degeneracy law}\index{monad transformers!non-degeneracy law}
of \lstinline!flift! and \lstinline!brun!. The law requires \lstinline!flift!
and \lstinline!brun! to preserve all information about $M$-effects.
The analogous non-degeneracy law for \lstinline!blift! and \lstinline!frun!
is
\[
\text{blift}\bef\text{frun}_{L}(\theta_{M})=\text{id}\quad.
\]


\subsection{Category-theoretic properties of lifts and runners\label{subsec:Category-theoretic-properties-of-lifts-and-runners-functors-in-category-of-monads}}

We have derived many laws of lifts and runners from heuristic considerations.
Let us turn to category theory for guidance about obtaining a simplified
and coherent picture of those laws.

The composition law~(\ref{eq:composition-law-of-frun}) suggests
that \lstinline!frun! is a lifting from monad morphisms $M\leadsto N$
to monad morphisms $T_{L}^{M}\leadsto T_{L}^{N}$. In the language
of category theory, a monad morphism is a morphism in the category
of monads. The category of monads has all possible monads ($M$, $N$,
...) as its objects and all possible monad morphisms (of type $M\leadsto N$)
as its morphisms. 

Note that \lstinline!frun! obeys the laws of identity and composition;
these are the laws of a (categorical) functor. Looking at the law~(\ref{eq:composition-law-of-frun}),
we find that \lstinline!frun! maps morphisms between monads ($M$,
$N$, etc.) to morphisms between monad stacks with base $L$ (such
as $T_{L}^{M}$, $T_{L}^{N}$, etc.). 

So, let us consider the category of monad stacks with a fixed base
monad $L$. The objects of that category are all monad stacks $T_{L}^{M}$,
$T_{L}^{N}$, etc., with the same base monad. The morphisms of that
category are all monad morphisms between those monad stacks. (Since
monad stacks are themselves monads, the category of monad stacks with
base $L$ is a sub-category of the category of monads\index{monads!category of}.) 

We can now observe that \lstinline!frun! plays the role of the \lstinline!map!
function for a (categorical) functor from the category of monads to
the category of monad stacks with base $L$. That functor (which we
may denote by $T_{L}^{\bullet}$) maps each monad $M$ to the stack
$T_{L}^{M}$, and each monad morphism $\phi:M\leadsto N$ to a monad
morphism $\text{frun}_{L}(\phi):T_{L}^{M}\leadsto T_{L}^{N}$. We
may view the functor $T_{L}^{\bullet}$ as the \textsf{``}bare\textsf{''} monad transformer,
not yet applied to a foreign monad $M$.

Note that the functor $T_{L}$ maps the monad $M$ to the stack $T_{L}^{M}$;
it maps objects of one category to objects of another. It is not a
function from \emph{values} of type $M^{A}$ to values of type $T_{L}^{M,A}$.
That function is \lstinline!flift!. What is the role of \lstinline!flift!
in the category of monads? The function \lstinline!flift! works in
the same way for any foreign monad $M$ because the code of \lstinline!flift!
is parametric in the type constructor $M$. So, let us look at the
relationship between the functions \lstinline!flift! applied to different
foreign monads.

Assume $M$ and $N$ are some monads for which a monad morphism $\phi:M^{A}\leadsto N^{A}$
exists. We may use \lstinline!flift! to transform $M^{A}$ into $T_{L}^{M,A}$
or to transform $N^{A}$ into $T_{L}^{N,A}$. But we can also obtain
a monad morphism $T_{L}^{M}\leadsto T_{L}^{N}$ as $\text{frun}_{L}\left(\phi\right)$.
These monad morphisms can be drawn as a square diagram.\begin{wrapfigure}{l}{0.22\columnwidth}%
\vspace{-1.65\baselineskip}
\[
\xymatrix{\xyScaleY{1.6pc}\xyScaleX{2.1pc}M^{A}\ar[d]\sb(0.45){\phi}\ar[r]\sp(0.5){\text{flift}} & T_{L}^{M,A}\ar[d]\sp(0.45){\text{frun}_{L}(\phi)}\\
N^{A}\ar[r]\sp(0.5){\text{flift}} & T_{L}^{N,A}
}
\]

\vspace{-2\baselineskip}
\end{wrapfigure}%
The diagram will commute if the following \index{monadic naturality law!of flift@of \texttt{flift}}\textbf{monadic
naturality law} holds:
\begin{equation}
\text{flift}_{L}^{M,A}\bef\text{frun}_{L}(\phi^{:M^{A}\rightarrow N^{A}})=\phi\bef\text{flift}_{L}^{N,A}\quad.\label{eq:monadic-naturality-law-of-flift}
\end{equation}
Is it reasonable to require this law? To get some intuition, consider
three special cases where the law is simplified, namely $M=\text{Id}$,
$N=\text{Id}$, or $M=N$. 

When $M=\text{Id}$, we must choose $\phi$ as the monad morphism
$\phi\triangleq\text{pu}_{N}:\text{Id}\leadsto N$. (Exercise~\ref{subsec:Exercise-monad-transformer-extra-layer}
shows that there are no other monad morphisms between $\text{Id}$
and $N$.) The monad stack $T_{L}^{M}$ is simplified to $T_{L}^{\text{Id}}\cong L$.
The function $\text{flift}_{L}^{M,A}$ has type signature $\text{Id}^{A}\rightarrow T_{L}^{M,A}$,
which is the same as $A\rightarrow L^{A}$. For a general monad $L$,
there is no other function of this type except $\text{pu}_{L}$; so,
$\text{flift}_{L}^{\text{Id}}$ must be equal to $\text{pu}_{L}$.
The monad morphism $\text{frun}_{L}(\phi)$ has type signature $T_{L}^{M}\leadsto T_{L}^{N}$,
which is the same as $L\leadsto T_{L}^{N}$, the type of \lstinline!blift!.
Since the monad $N$ is arbitrary, it is reasonable to assume that
\[
\text{frun}_{L}(\phi)=\text{frun}_{L}(\text{pu}_{N})=\text{blift}_{L}^{N}\quad.
\]
In this way, the monadic naturality law~(\ref{eq:monadic-naturality-law-of-flift})
gives the equation
\[
\text{pu}_{L}\bef\text{blift}_{L}^{N}=\text{pu}_{N}\bef\text{flift}_{L}^{N}\quad.
\]
This equation holds due to the identity laws of lifts:
\[
\text{pu}_{L}\bef\text{blift}_{L}^{N}=\text{pu}_{T_{L}^{N}}\quad,\quad\quad\text{pu}_{N}\bef\text{flift}_{L}^{N}=\text{pu}_{T_{L}^{N}}\quad.
\]

When $N=\text{Id}$, we choose $\phi=\theta_{M}$, assuming that $M$
has a runner. The monad stack $T_{L}^{N}$ is simplified to $T_{L}^{\text{Id}}\cong L$.
The function $\text{flift}_{L}^{N}$ has type signature $A\rightarrow L^{A}$
and is equal to $\text{pu}_{L}$. So, we get:
\[
\text{flift}_{L}^{M}\bef\text{frun}_{L}(\theta_{M})=\theta_{M}\bef\text{pu}_{L}\quad.
\]
This is the \textsf{``}purity\textsf{''} law of \lstinline!flift! that we derived
earlier.

When $M=N$, we may choose $\phi=\text{id}$. The monadic naturality
law~(\ref{eq:monadic-naturality-law-of-flift}) becomes
\[
\text{flift}\bef\text{frun}_{L}(\text{id})=\text{flift}\quad.
\]
This equation holds as long as \lstinline!frun! satisfies the identity
law of monad morphisms.

So, we found that the law~(\ref{eq:monadic-naturality-law-of-flift})
agrees with previously derived laws and, moreover, covers one of the
laws of runners. The interpretation of the monadic naturality law
becomes clear from viewing \lstinline!frun! as a lifting (\textsf{``}\lstinline!map!\textsf{''})
corresponding to the functor $T_{L}$. Denoting that lifting temporarily
by $^{\uparrow T_{L}}$, we rewrite the law~(\ref{eq:monadic-naturality-law-of-flift})
as
\[
\text{flift}\bef\phi^{\uparrow T_{L}}=\phi\bef\text{flift}\quad.
\]
This is a standard form of a naturality law if we view $\text{flift}^{M}:M\leadsto T_{L}^{M}$
as a \index{natural transformation!in the category of monads}natural
transformation between the identity functor $\text{Id}^{M}\triangleq M$
(in the category of monads) to the functor $T_{L}^{\bullet}$, the
monad transformer functor with the base monad $L$. The law expresses
the property that the code of \lstinline!flift! works in the same
way for all foreign monads $M$. We call it a \textsf{``}\textbf{monadic}\textsf{''}
naturality law\index{monadic naturality law!of foreign runner (frun)@of foreign runner (\texttt{frun})}
because $\text{flift}_{L}^{M,A}:M^{A}\rightarrow T_{L}^{M,A}$ also
satisfies the ordinary naturality law with respect to the type parameter
$A$, for a fixed monad $M$.

What other runners have monadic naturality properties? Consider the
base runner, $\text{brun}_{L}:T_{L}^{M}\leadsto M$, assuming it exists
for the chosen base monad $L$. Viewed in the category of monads,
this function is a natural transformation between the functor $T_{L}^{\bullet}$
and the identity functor (going in the opposite way compared with
\lstinline!flift!). The corresponding \textbf{monadic naturality
law}\index{monadic naturality law!of base runner (brun)@of base runner (\texttt{brun})}
is
\[
\text{brun}_{L}^{M}\bef\phi^{:M\leadsto N}=\phi^{\uparrow T_{L}}\bef\text{brun}_{L}^{N}=\text{frun}_{L}(\phi)\bef\text{brun}_{L}^{N}\quad.
\]
To see whether it is reasonable to assume this law, let us derive
some consequences using specific choices of $M$ and $N$.

With $M=\text{Id}$, the function $\phi$ must be $\phi=\text{pu}_{N}$
(Exercise~\ref{subsec:Exercise-monad-transformer-extra-layer}),
while $\text{frun}_{L}(\phi):T_{L}^{\text{Id}}\leadsto T_{L}^{N}$
is equal to the base lift function ($\text{blift}_{L}^{N}$). We also
have $\text{brun}_{L}^{\text{Id}}:T_{L}^{\text{Id}}\leadsto\text{Id}$,
so this function is equal to $L$\textsf{'}s runner ($\text{brun}_{L}^{\text{Id}}=\theta_{L}$).
The resulting equation is the purity law of \lstinline!blift! and
\lstinline!brun!:
\[
\theta_{L}\bef\text{pu}_{N}=\text{blift}_{L}^{N}\bef\text{brun}_{L}^{N}\quad.
\]

With $N=\text{Id}$, the function $\phi$ must be a runner ($\theta_{M}$),
while $\text{brun}_{L}^{\text{Id}}=\theta_{L}$ as before. We get
\[
\text{brun}_{L}^{M}\bef\theta_{M}=\text{frun}_{L}(\theta_{M})\bef\theta_{L}\quad.
\]
This is the commutativity law of runners we obtained earlier.

So, the monadic naturality law of \lstinline!brun! covers two of
the previously formulated laws.

The monadic naturality law of \lstinline!frun! is equivalent to \lstinline!frun!\textsf{'}s
composition law:\footnote{This is similar to the fact that the naturality law and the composition
law are the same for \lstinline!fmap!.}
\[
\text{frun}_{L}(\phi^{:M\leadsto N})\bef\chi^{\uparrow T_{L}}=\text{frun}_{L}(\phi)\bef\text{frun}_{L}(\chi)=\text{frun}_{L}(\phi\bef\chi)\quad.
\]

Since the category of monad stacks is a sub-category of the category
of monads, $T_{L}$ is an \emph{endofunctor}\index{endofunctor!in the category of monads}
in the category of monads, such that a natural transformation $\text{flift}_{L}:\text{Id}^{M}\leadsto T_{L}^{M}$
exists (in the sense of the category of monads, i.e., parametric in
the monad $M$ and obeying the monad morphism laws). 

Endofunctors $F^{A}$ having a natural transformation $\text{pu}_{F}:\text{Id}^{A}\rightarrow F^{A}$
are \textsf{``}pointed\textsf{''}\index{pointed functor!in the category of monads};
those with a natural transformation $\text{ex}_{F}:F^{A}\rightarrow\text{Id}^{A}$
are \textsf{``}co-pointed\textsf{''}\index{co-pointed functor!in the category of monads}.
Naturality forces the non-degeneracy law $\text{pu}_{F}\bef\text{ex}_{F}=\text{id}$.
We find that $T_{L}$ is a pointed endofunctor in the category of
monads. If the transformer $T_{L}$ has a base runner ($\text{brun}_{L}:T_{L}^{M}\leadsto\text{Id}^{M}$)
then $T_{L}$ will be also co-pointed.

It is remarkable that all the laws of monad transformers can be derived
from a single (but more abstract) definition: a monad transformer
$T$ is \emph{just a pointed and co-pointed endofunctor in the category
of monads}.\footnote{\textsf{``}\emph{What\textsf{'}s the problem?}\textsf{''} as the joke would go.}
Such a endofunctor $T$ maps monads $M$, $N$, etc., to monads $T^{M}$,
$T^{N}$, etc. Suppose we were given such a $T$ but were not told
that it is a monad transformer for some base monad. Still, we can
recover its base monad $L$ as the image of the identity monad:
\[
L\triangleq T^{\text{Id}}\quad.
\]
The definition of $T$ already specifies functions \lstinline!flift!,
\lstinline!frun!, and \lstinline!brun! as the natural transformations
\[
\text{flift}_{T}^{M}:\text{Id}^{M}\leadsto T^{M}\quad,\quad\quad\text{brun}_{T}^{M}:T^{M}\leadsto\text{Id}^{M}\quad,\quad\quad\text{frun}_{T}^{M,N}:(M\leadsto N)\rightarrow T^{M}\leadsto T^{N}\quad.
\]
The functor laws and the monadic naturality laws for those transformations
will then enforce the 18 laws of monad transformers. In this way,
a single definition expresses all monad transformer laws.

\paragraph{The non-degeneracy law of \texttt{brun}}

Is the non-degeneracy law ($\text{flift}_{T}\bef\text{brun}_{T}=\text{id}$)
a consequence of monadic naturality of \lstinline!brun!? It may be,
but this book does not have a proof. The composition of two natural
transformations is again a natural transformation; this is true in
any category, including the category of monads. So, the composition
($\text{flift}\bef\text{brun}$) is a natural transformation of type
$\text{Id}^{\bullet}\leadsto\text{Id}^{\bullet}$; but it is a natural
transformation \emph{in the category of monads} (rather than in the
category of all functors). To show that this natural transformation
is equal to an identity function, we would need to prove that there
are no other natural transformations between identity functors in
the category of monads.

A natural transformation of type $\text{Id}^{\bullet}\leadsto\text{Id}^{\bullet}$
means, by definition, a family of monad morphisms $\varepsilon^{M}:M\leadsto M$
that work the same way for every monad $M$. One such morphism is
the identity function, $\varepsilon=\text{id}$. However, it is not
clear (Problem~\ref{par:Problem-identity-natural-monad-morphism})
whether there exist non-identity monad morphisms $M\leadsto M$ that
work the same way for every monad $M$. For instance, Exercise~\ref{subsec:Exercise-monad-transformer-extra-layer-3}
shows a failed attempt to define such a monad morphism.

Since we have not shown that the non-degeneracy law for base runners
automatically follows from monadic naturality, we will need to verify
that law separately whenever the base runner exists.

\subsection{Summary of the laws of monad transformers\label{subsec:Laws-of-monad-transformers}}

We have found that a \textbf{monad transformer}\index{monad transformers!full definition}
\textbf{for a base monad} $L$ is a type constructor $T_{L}^{M,A}$
with a type parameter $A$ and a monad parameter $M$, such that the
following laws hold:
\begin{enumerate}
\item \textbf{Monad law}s: $T_{L}^{M,\bullet}$ is a lawful monad for any
monad $M$.\index{monad transformers!monad laws} (The functor $T_{L}^{M,\bullet}$
has methods $\text{pu}_{T}$ and $\text{ftn}_{T}$ that satisfy the
monad laws.)
\item \textbf{Identity law}s:\index{monad transformers!identity law} $T_{L}^{\text{Id},\bullet}\cong L^{\bullet}$
via a monad isomorphism, where $\text{Id}$ is the identity monad
($\text{Id}^{A}\triangleq A$).
\item \textbf{Lifting law}s:\index{monad transformers!lifting law} There
is a function $\text{flift}_{L}:M^{A}\rightarrow T_{L}^{M,A}$ (in
a shorter notation, $\text{flift}_{L}:M\leadsto T_{L}^{M}$) that
works parametrically in the monad $M$ and obeys the laws of monad
morphisms.
\item \textbf{Runner laws}:\index{monad transformers!runner laws} There
is a \textsf{``}foreign runner\textsf{''}\footnote{This function is called \lstinline!hoist! in Haskell standard libraries
and in \texttt{scalaz}.} $\text{frun}\left(\phi\right)$ such that for any monads $M$, $N$
and any monad morphism $\phi:M\leadsto N$, the function $\text{frun}\left(\phi\right):T_{L}^{M}\leadsto T_{L}^{N}$
is a monad morphism. The function \lstinline!frun! lifts monad morphisms
from $M\leadsto N$ to $T_{L}^{M}\leadsto T_{L}^{N}$ and must satisfy
the corresponding \textbf{functor laws}\index{monad transformers!functor laws of runner}:
\[
\text{frun}\left(\text{id}\right)=\text{id}\quad,\quad\quad\text{frun}\left(\phi\right)\bef\text{frun}\left(\chi\right)=\text{frun}\left(\phi\bef\chi\right)\quad.
\]
It follows from the identity law $T_{L}^{\text{Id}}\cong L$ that
the base monad $L$ can be lifted into $T_{L}^{M}$. Namely, by computing
$\text{frun}\left(\phi\right)$ with $\phi\triangleq\text{pu}_{M}:\text{Id}\leadsto M$,
we obtain a function called the \index{monad transformers!base lift}\textbf{base
lift} (\lstinline!blift!):
\[
\text{blift}:T_{L}^{\text{Id}}\leadsto T_{L}^{M}\cong L\leadsto T_{L}^{M}\quad,\quad\quad\text{blift}\triangleq\text{frun}\,(\text{pu}_{M})\quad.
\]
The base lift automatically satisfies the non-degeneracy law,
\[
\text{blift}\bef\text{frun}\,(\phi^{:M\leadsto\text{Id}})=\text{id}\quad,
\]
for any monad morphism $\phi:M\leadsto\text{Id}$, because the left-hand
side equals $\text{frun}\,(\text{pu}_{M}\bef\phi)$, and the composition
law for monad morphisms gives $\text{pu}_{M}\bef\phi=\text{pu}_{\text{Id}}=\text{id}$.
\item \textbf{Base runner laws}:\index{monad transformers!base runner laws}
There is a \textbf{base runner}, a monad morphism $\text{brun}_{L}^{M}:T_{L}^{M}\leadsto M$
defined parametrically in the monad $M$. The base runner must also
satisfy the \textbf{non-degeneracy law},\index{monad transformers!non-degeneracy law}
\[
\text{flift}_{L}^{M}\bef\text{brun}_{L}^{M}=\text{id}\quad.
\]
Since monad transformers are specific to their base monad and do not
support a transition to another base monad, there are no functor laws
for \lstinline!brun!, unlike \lstinline!frun!. Some monads have
a general base runner, $\text{brun}\,(\theta_{L})$, parameterized
by an arbitrary runner $\theta_{L}:L\leadsto\text{Id}$. If so, the
function $\text{brun}\,(\theta_{L})$ must obey the base runner laws
for any fixed $\theta_{L}$.
\item \textbf{Monadic naturality laws}: \index{monadic naturality law}
The functions \lstinline!flift! and \lstinline!brun! must satisfy
the monadic naturality law with respect to the monad parameter $M$.
For an arbitrary monad morphism $\phi:M\leadsto N$,
\begin{align*}
{\color{greenunder}\text{monadic naturality law of }\text{flift}:}\quad & \text{flift}^{M}\bef\text{frun}\,(\phi^{:M\leadsto N})=\phi^{:M\leadsto N}\bef\text{flift}^{N}\quad,\\
{\color{greenunder}\text{monadic naturality law of }\text{brun}:}\quad & \text{brun}^{M}\bef\phi^{:M\leadsto N}=\text{frun}\,(\phi^{:M\leadsto N})\bef\text{brun}^{N}\quad.
\end{align*}
\end{enumerate}
It turns out that we can equally well impose the monadic naturality
law of \lstinline!flift! with an arbitrary natural transformation
$\phi:M^{A}\rightarrow N^{A}$, without the requirement that $\phi$
be a monad morphism.

In total, we found 18 laws for monad transformers. Are all these laws
necessary? 

The main use of the laws is to verify correctness of the code. The
next section shows some examples of incorrect implementations of monad
transformers and indicates the laws that are violated.

\subsection{Examples of invalid monad transformers}

The laws of monad transformers guarantee that the transformed monad
is able to represent, without loss of information, the operations
of the base monad as well as the operations of the foreign monad.
If some of these laws are omitted, we risk accepting a transformer
that has all the methods with the required type signatures but does
not work correctly.

The simplest example of an invalid monad transformer is obtained by
defining the new monad to be the unit monad ($T_{L}^{M,A}\triangleq\bbnum 1$)
for any monads $L$ and $M$. This \textsf{``}fake transformer\textsf{''} cannot possibly
describe the effects of $L$ and $M$, because the methods of the
unit monad discard \emph{all} information and return $1$. However,
the type constructor $T_{L}^{M,A}$ has the required methods $\text{pu}_{T}$,
$\text{ftn}_{T}$, $\text{flift}_{L}$, and $\text{frun}_{L}$ (they
are constant functions returning $1$). All these functions are automatically
monad morphisms, since a function from any monad to the unit monad
is always a monad morphism. So, the \textsf{``}fake transformer\textsf{''} actually
satisfies many of the monad transformer laws! However, the identity
law $T_{L}^{\text{Id}}\cong L$ is violated since $T_{L}^{\text{Id}}=\bbnum 1\not\cong L$.
For this reason, $T_{L}^{M,A}\triangleq\bbnum 1$ is not a lawful
monad transformer.

Other examples of incorrect \textsf{``}transformers\textsf{''} violating some of the
laws are $T_{L}^{M}\triangleq L$ (no lifting law) and $T_{L}^{M}\triangleq M$
(no identity law).

These examples demonstrate the importance of the monad transformer
laws. A wrong implementation of a \textsf{``}transformer\textsf{''} could fail to
represent properly the effects of the monads, even though the transformer\textsf{'}s
methods with the correct type signatures are provided. The only way
for us to detect the problem is to establish a violation of some of
the required laws.

In these cases, it is intuitively clear that the transformer definitions
are incorrect because the information about either $L$ or $M$ is
missing in the type $T_{L}^{M}$. A valid definition of $T_{L}^{M}$
must be a type constructor that somehow combines the type constructors
$L$ and $M$. Many such definitions are possible, but few will satisfy
the monad transformer laws, as the next subsection shows.

\subsection{Examples of failure to define a generic monad transformer}

No type construction is known that works in the same way for all monad
pairs $L$, $M$ and correctly combines the effects of both monads
(i.e., satisfies the laws of monad transformers). We will now consider
a few different ways of combining the type constructors $L$ and $M$.
In all cases, we will find that some monad transformer laws are violated.

Simple ways of combining two type constructors $L^{\bullet}$ and
$M^{\bullet}$ are functor composition ($L^{M^{\bullet}}$ or $M^{L^{\bullet}}$),
product ($L^{\bullet}\times M^{\bullet}$), and co-product ($L^{\bullet}+M^{\bullet}$).

\paragraph{Functor composition}

As we have seen, the functor composition works only for certain monads
and only in a certain order; so it cannot serve as a generic monad
transformer. A simple counterexample is $L^{A}\triangleq\bbnum 1+A$
and $M^{A}\triangleq A\times A$ where $M^{L^{A}}=\left(\bbnum 1+A\right)\times\left(\bbnum 1+A\right)$
is a monad but $L^{M^{A}}=\bbnum 1+A\times A$ is not (see Exercise~\ref{subsec:Exercise-1-monads-7}).
Another counterexample is the \lstinline!State! monad, $\text{State}_{S}^{A}\triangleq S\rightarrow S\times A$.
The \lstinline!State! monad does not compose with arbitrary monads
$M$ in either order; for instance, $\bbnum 1+\text{State}_{S}^{A}$
and $\text{State}_{S}^{Z\rightarrow A}$ are not monads (Examples~\ref{subsec:Example-state-monad-composition-fails-with-option}
and~\ref{subsec:Example-state-monad-composition-fails-with-reader}). 

\paragraph{Functor product}

We know from Chapter~\ref{chap:Semimonads-and-monads} that the functor
product $M_{1}^{A}\times M_{2}^{A}$ is a monad when $M_{1}$ and
$M_{2}$ are themselves monads. However, the product $M_{1}^{A}\times M_{2}^{A}$
describes two separate computations with two separate effects. Instead,
we need a single computation with a combined effect. Formally, we
find that there is no naturally defined $\text{flift}:M^{A}\rightarrow L^{A}\times M^{A}$
because we cannot create values of type $L^{A}$ out of values of
type $M^{A}$ when monads $L$ and $M$ are arbitrary.

\paragraph{Functor co-product}

The functor co-product $L^{\bullet}+M^{\bullet}$ is in general not
a monad when $L$ and $M$ are arbitrary monads. A simple counterexample
is found by using two \lstinline!Reader! monads, $L^{A}\triangleq P\rightarrow A$
and $M^{A}\triangleq Q\rightarrow A$. The co-product $\left(P\rightarrow A\right)+\left(Q\rightarrow A\right)$
is not a monad (Exercise~\ref{subsec:Exercise-1-monads-6}). But
even if $L^{\bullet}+M^{\bullet}$ were a monad, the result would
be a \emph{choice} between two different effectful computations, not
a single computation with a combined effect.

\paragraph{Using the free monad}

The functor composition $L^{M^{\bullet}}$ and the co-product $L^{\bullet}+M^{\bullet}$
may not always be monads, but they are always functors. We can make
monads out of those functors by using the free monad construction.
So, we obtain $\text{Free}^{L^{M^{\bullet}}}$, the free monad over
$L^{M^{\bullet}}$, and $\text{Free}^{L^{\bullet}+M^{\bullet}}$,
the free monad over $L^{\bullet}+M^{\bullet}$. Many laws of the monad
transformers are satisfied by these constructions. However, the identity
laws fail because
\[
\text{Free}^{L^{\text{Id}^{\bullet}}}\cong\text{Free}^{L^{\bullet}}\not\cong L\quad,\quad\quad\text{Free}^{L^{\bullet}+\text{Id}^{\bullet}}\not\cong L\quad.
\]
The lifting laws are also violated because $\text{flift}:M^{A}\rightarrow\text{Free}^{L^{\bullet}+M^{\bullet},A}$
is not a monad morphism: it maps $\text{pu}_{M}$ into a non-pure
value of the free monad. Nevertheless, these constructions are not
useless. Once we run the free monad into a concrete (non-free) monad,
we could arrange to hide the violations of these laws, so that the
monad laws hold for the resulting (non-free) monad.

\paragraph{\textsf{``}Day convolution\textsf{''}}

The construction called \textsf{``}\textbf{Day convolution\index{Day convolution}}\textsf{''}
defines a new functor $L\star M$ as 
\begin{equation}
\left(L\star M\right)^{A}\triangleq\exists P.\:\exists Q.\,\left(P\times Q\rightarrow A\right)\times L^{P}\times M^{Q}\quad.\label{eq:definition-of-monoidal-convolution}
\end{equation}
This formula can be seen as a modified application of the co-Yoneda
identities
\[
L^{A}\cong\exists P.\,L^{P}\times\left(P\rightarrow A\right)\quad,\quad\quad M^{A}\cong\exists Q.\,M^{Q}\times\left(Q\rightarrow A\right)\quad.
\]
The functor product $L^{A}\times M^{A}$ is equivalent to $\exists P.\,\exists Q.\,L^{P}\times M^{Q}\times\left(P+Q\rightarrow A\right)$:
\begin{align}
 & L^{A}\times M^{A}\nonumber \\
{\color{greenunder}\text{co-Yoneda identities for }L^{A}\text{ and }M^{A}:}\quad & \cong\exists P.\,L^{P}\times\gunderline{\left(P\rightarrow A\right)}\times\exists Q.\,M^{Q}\times\gunderline{\left(Q\rightarrow A\right)}\nonumber \\
{\color{greenunder}\text{equivalence in Eq.~(\ref{eq:equivalence-pq-a-for-monoidal-convolution})}:}\quad & \cong\exists P.\,\exists Q.\,L^{P}\times M^{Q}\times\left(P+Q\rightarrow A\right)\label{eq:product-l-m-for-monoidal-convolution}
\end{align}
where we used the type equivalence 
\begin{equation}
\left(P\rightarrow A\right)\times\left(Q\rightarrow A\right)\cong P+Q\rightarrow A\quad.\label{eq:equivalence-pq-a-for-monoidal-convolution}
\end{equation}
If we (arbitrarily) replace $P+Q$ by $P\times Q$ in Eq.~(\ref{eq:product-l-m-for-monoidal-convolution}),
we will obtain Eq.~(\ref{eq:definition-of-monoidal-convolution}).

The Day convolution $L\star M$ is associative\footnote{\texttt{\href{https://en.wikipedia.org/wiki/Day_convolution}{https://en.wikipedia.org/wiki/Day\_convolution}}}
and always produces a functor since Eq.~(\ref{eq:definition-of-monoidal-convolution})
is covariant in $A$. A simple example where the Day convolution fails
to produce a monad transformer is $L^{A}\triangleq1+A$ and $M^{A}\triangleq R\rightarrow A$.
We compute the functor $L\star M$:
\begin{align*}
 & \left(L\star M\right)^{A}\\
{\color{greenunder}\text{definitions of }L,M,\star:}\quad & \cong\exists P.\,\exists Q.\,\gunderline{\left(P\times Q\rightarrow A\right)}\times\left(\bbnum 1+P\right)\times\left(R\rightarrow Q\right)\\
{\color{greenunder}\text{curry the arguments, move a quantifier}:}\quad & \cong\exists P.\left(\bbnum 1+P\right)\times\gunderline{\exists Q.\left(Q\rightarrow P\rightarrow A\right)\times\left(R\rightarrow Q\right)}\\
{\color{greenunder}\text{co-Yoneda identity with }\exists Q:}\quad & \cong\exists P.\left(\bbnum 1+P\right)\times\left(\gunderline{R\rightarrow P}\rightarrow A\right)\\
{\color{greenunder}\text{swap curried arguments}:}\quad & \cong\exists P.\left(\bbnum 1+P\right)\times\left(P\rightarrow R\rightarrow A\right)\\
{\color{greenunder}\text{co-Yoneda identity with }\exists P:}\quad & \cong\bbnum 1+\left(R\rightarrow A\right)\quad.
\end{align*}
This functor is not a monad (see Exercise~\ref{subsec:Exercise-1-monads-7}),
so the transformer\textsf{'}s monad law fails.

The Day convolution works because the type-level operations $P+Q$
and $P\times Q$ are both monoidal, in a suitable sense. We could
generalize the Day convolution to use another monoidal type-level
operation, such as $P+Q+Z\times P\times Q$ (where $Z$ is a fixed
type), instead of $P\times Q$. The result is a different \textsf{``}monoidal
convolution\textsf{''} ($\star_{Z}$):
\[
\left(L\star_{Z}M\right)^{A}\triangleq\exists P.\:\exists Q.\,\left(P+Q+Z\times P\times Q\rightarrow A\right)\times L^{P}\times M^{Q}\quad.
\]
But this construction also fails to produce a lawful monad transformer.

\paragraph{Using a codensity monad}

The type constructor 
\[
\text{Cod}^{F,A}\triangleq\forall B.\,(A\rightarrow F^{B})\rightarrow F^{B}
\]
is called the \index{codensity monad}\textbf{codensity monad} on
a functor $F$. The codensity monad provides yet another way of making
a monad out of any functor. Can we then combine arbitrary monads $L$,
$M$ into a new monad? It turns out that the codensity construction
does not provide enough properties to create a usable monad transformer.
Here are some attempts:

\textbf{(1)} The codensity monad on $L\circ M$,
\[
F^{A}\triangleq\forall B.\,\big(A\rightarrow L^{M^{B}}\big)\rightarrow L^{M^{B}}\quad,
\]
does not support a lift $M^{A}\rightarrow F^{A}$. Intuitively, the
reason is that we can use values of types $M^{A}$ and $A\rightarrow L^{M^{B}}$
only in one way: using \lstinline!map! to transform $M^{A}$ into
$M^{L^{M^{B}}}$. We cannot exchange the layers of $M$ and $L$ when
those monads are arbitrary, and so we cannot obtain a value of type
$L^{M^{B}}$. A simple counterexample is found with $L^{A}\triangleq\bbnum 1+A$
and $M^{A}\triangleq Z\rightarrow A$ for a fixed type $Z$: the type
signature
\[
(Z\rightarrow A)\rightarrow(A\rightarrow\bbnum 1+(Z\rightarrow B))\rightarrow\bbnum 1+(Z\rightarrow B)
\]
can be implemented only as a function that returns a constant unit
value ($1+\bbnum 0^{:Z\rightarrow B}$), which loses information.
Formally, a constant function would violate the identity law of monad
morphisms.

\textbf{(2)} The composition of $\text{Cod}^{L,\bullet}$ and $M^{\bullet}$
yields the following type constructor:
\[
F^{A}\triangleq\forall B.\,(M^{A}\rightarrow L^{B})\rightarrow L^{B}\quad.
\]
However, this $F^{A}$ fails to be a monad for all $L$ and $M$.
A counterexample is $L^{A}\triangleq S\rightarrow A$ and $M^{A}\triangleq R\rightarrow A$,
for which the Yoneda identity gives:
\begin{align*}
 & F^{A}=\forall B.\,(\gunderline{(R\rightarrow A)\rightarrow S}\rightarrow B)\rightarrow S\rightarrow B\cong\forall B.\,(\gunderline{(R\rightarrow A)\times S}\rightarrow B)\rightarrow L^{B}\\
 & \cong L^{(R\rightarrow A)\times S}=S\rightarrow\left(R\rightarrow A\right)\times S\quad.
\end{align*}
The last type constructor is not a monad: it is a composition of the
\lstinline!Reader! and \lstinline!State! monads in the wrong order
(see Statement~\ref{subsec:Example-state-monad-composition-fails-with-reader}).

\textbf{(3)} Consider the \textbf{composed codensity monad}\index{codensity monad!composed},
defined by
\[
\text{Cod}_{L}^{M,A}\triangleq\forall X.\,(A\rightarrow L^{X})\rightarrow L^{M^{X}}\quad.
\]
This type constructor can be viewed as the continuation monad transformer
for the base monad $\forall X.\,(A\rightarrow X)\rightarrow M^{X}\cong M^{A}$
(this equivalence is a Yoneda identity). Although $\text{Cod}_{L}^{M,A}$
is a lawful monad (Statement~\ref{par:Exercise-combined-codensity-monad}),
it cannot serve as a monad transformer because the lift $M^{A}\rightarrow\text{Cod}_{L}^{M,A}$
does not exist for some $L$ and $M$. A simple counterexample is
found with $M^{A}\triangleq R\rightarrow A$ and $L^{A}\triangleq\bbnum 1+A$
similarly to the counterexample shown in (1).

\subsection{Functor composition with transformed monads}

Suppose we are working with a base monad $L$ and a foreign monad
$M$, and we have constructed the transformed monad $T_{L}^{M}$.
In this section, let us denote the transformed monad simply by $T$. 

The main feature of a monad transformer is that the monad $T$ adequately
describes the effects of both monads $L$ and $M$ at the same time.
Suppose we are working with a deeply nested type constructor involving
many functor layers of monads $L$, $M$, and $T$ such as
\[
T^{M^{T^{L^{M^{L^{A}}}}}}=\left(T\circ M\circ T\circ L\circ M\circ L\right)^{A}\quad.
\]
The properties of the transformer allow us to convert this type to
a single layer of the monad $T$. In this example, we will have a
natural transformation
\[
\left(T\circ M\circ T\circ L\circ M\circ L\right)^{A}\rightarrow T^{A}\quad.
\]
To achieve this, we first use the methods \lstinline!blift! and \lstinline!flift!
to convert each layer of $L$ or $M$ to a layer of $T$, lifting
into functors as necessary. The result will be a number of nested
layers of $T$. Second, we use $\text{ftn}_{T}$ as many times as
necessary to flatten all nested layers of $T$ into a single layer.
The result will be a value of type $T^{A}$, as required. Due to the
laws of \lstinline!blift! and \lstinline!flift!, the result does
not depend on the order in which the different layers are converted
and flattened.

\subsection{Stacking two monads. Proofs\label{subsec:Stacking-two-monads}}

Suppose we know the transformers $T_{P}$ and $T_{Q}$ for some given
monads $P$ and $Q$. We can transform $Q$ with $P$ and obtain a
monad $R^{A}\triangleq T_{P}^{Q,A}$. The monad transformer $T_{R}$
for the monad $R$ is defined to be the following monad stack (see
Section~\ref{subsec:Combining-more-than-monad-stacks}):
\[
T_{R}^{M,A}\triangleq T_{P}^{T_{Q}^{M,\bullet},A}\triangleq(P\varangle Q\varangle M)^{A}\quad.
\]
Here, it is important that the monad $T_{Q}^{M,\bullet}$ is substituted
into $T_{P}^{M,A}$ as the foreign monad $M$ (not as the type parameter
$A$). This way of composition is called \textbf{stacking}\index{monad transformers!stacking}
the monad transformers. 

In Scala code, this \textsf{``}stacking\textsf{''} construction is written as
\begin{lstlisting}
type RT[M, A] = PT[QT[M, *], A]
\end{lstlisting}
The resulting monad is a \textbf{stack}\index{monads!stack of} of
three monads $P$, $Q$, and $M$. The order of monads in the stack
is significant: in general, there will be no monad isomorphism between
differently ordered stacks.

We will now prove that the transformer $T_{R}$ is lawful (satisfies
the laws stated in Section~\ref{subsec:Laws-of-monad-transformers}),
as long as both $T_{P}$ and $T_{Q}$ satisfy the same laws. To shorten
the notation, we talk about a \textsf{``}monad $T_{P}^{M}$\textsf{''} meaning the
monad defined as $T_{P}^{M,\bullet}$ or, more verbosely, the monad
$G^{A}\triangleq T_{P}^{M,A}$.

\paragraph{Monad laws}

We need to show that $T_{P}^{T_{Q}^{M}}$ is a monad for any monad
$M$. The monad laws for $T_{Q}$ say that $T_{Q}^{M}$ is a monad.
The monad laws for $T_{P}$ say that $T_{P}^{S}$ is a monad for any
monad $S$; in particular, for $S=T_{Q}^{M}$. Therefore, $T_{P}^{S}=T_{P}^{T_{Q}^{M}}$
is a monad.

\paragraph{Identity law}

We need to show that $T_{P}^{T_{Q}^{\text{Id}}}\cong T_{P}^{Q}$ via
a monad isomorphism. The identity law for $T_{Q}$ says that $T_{Q}^{\text{Id}}\cong Q$
via a monad isomorphism. So, we already have a monad morphism $\phi:Q\leadsto T_{Q}^{\text{Id}}$
and its inverse, $\chi:T_{Q}^{\text{Id}}\leadsto Q$. The runner $\text{frun}_{P}$
for $T_{P}$ can be applied to both $\phi$ and $\chi$ since they
are monad morphisms. So we obtain two new monad morphisms,
\[
\text{frun}_{P}\left(\phi\right):T_{P}^{Q}\leadsto T_{P}^{T_{Q}^{\text{Id}}}\quad;\quad\quad\text{frun}_{P}\left(\chi\right):T_{P}^{T_{Q}^{\text{Id}}}\leadsto T_{P}^{Q}\quad.
\]
Are these two monad morphisms inverses of each other? To show this,
we need to verify that
\[
\text{frun}_{P}\left(\phi\right)\bef\text{frun}_{P}\left(\chi\right)=\text{id}\quad,\quad\quad\text{frun}_{P}\left(\chi\right)\bef\text{frun}_{P}\left(\phi\right)=\text{id}\quad.
\]
By the runner laws for $T_{P}$, we have $\text{frun}_{P}\left(\text{id}\right)=\text{id}$
and $\text{frun}_{P}\left(f\right)\bef\text{frun}_{P}\left(g\right)=\text{frun}_{P}\left(f\bef g\right)$
for any two monad morphisms $f$ and $g$. So, 
\begin{align*}
\text{frun}_{P}\left(\phi\right)\bef\text{frun}_{P}\left(\chi\right) & =\text{frun}_{P}\left(\phi\bef\chi\right)=\text{frun}_{P}\left(\text{id}\right)=\text{id}\quad,\\
\text{frun}_{P}\left(\chi\right)\bef\text{frun}_{P}\left(\phi\right) & =\text{frun}_{P}\left(\chi\bef\phi\right)=\text{frun}_{P}\left(\text{id}\right)=\text{id}\quad.
\end{align*}
We have indeed obtained a monad isomorphism between $T_{P}^{Q}$ and
$T_{P}^{T_{Q}^{\text{Id}}}$.

\paragraph{Lifting law}

We need to show that there exists a monad morphism $\text{flift}_{R}:M\leadsto T_{P}^{T_{Q}^{M}}$
for any monad $M$. The lifting law for $T_{Q}$ gives a monad morphism
$\text{flift}_{Q}:M\leadsto T_{Q}^{M}$. The lifting law for $T_{P}$
can be applied to the monad $T_{Q}^{M}$, which gives a monad morphism
$\text{flift}_{P}:T_{Q}^{M}\leadsto T_{P}^{T_{Q}^{M}}$. The composition
$\text{flift}_{R}\triangleq\text{flift}_{Q}\bef\text{flift}_{P}$
has the required type $M\leadsto T_{P}^{T_{Q}^{M}}$ and is a monad
morphism by Statement~\ref{subsec:Statement-monadic-morphism-composition}.

\paragraph{Runner law}

We need to show that there exists a lifting 
\[
\text{frun}_{R}:\left(M\leadsto N\right)\rightarrow T_{P}^{T_{Q}^{M}}\leadsto T_{P}^{T_{Q}^{N}}\quad.
\]
First, we have to define $\text{frun}_{R}(\phi)$ for any given $\phi:M\leadsto N$.
We use the lifting law for $T_{Q}$ to get a monad morphism
\[
\text{frun}_{Q}(\phi):T_{Q}^{M}\leadsto T_{Q}^{N}\quad.
\]
Now we can apply the lifting law for $T_{P}$ to this monad morphism
and obtain
\[
\text{frun}_{P}\big(\text{frun}_{Q}(\phi)\big):T_{P}^{T_{Q}^{M}}\leadsto T_{P}^{T_{Q}^{N}}\quad.
\]
This function has the correct type signature. So we can define
\[
\text{frun}_{R}\triangleq\text{frun}_{Q}\bef\text{frun}_{P}\quad.
\]
It remains to prove that $\text{frun}_{R}$ is a lawful lifting. We
use the fact that both $\text{flift}_{P}$ and $\text{flift}_{Q}$
are lawful liftings; we need to show that their composition is also
a lawful lifting. To verify the identity law of lifting, apply $\text{flift}_{R}$
to an identity function $\text{id}:M\leadsto M$,
\begin{align*}
 & \text{frun}_{R}(\text{id}^{:M\leadsto M})=\text{frun}_{P}\gunderline{\big(\text{frun}_{Q}(\text{id}^{:M\leadsto M})\big)}\\
{\color{greenunder}\text{identity law of }\text{frun}_{Q}:}\quad & =\text{frun}_{P}\big(\text{id}^{:T_{Q}^{M}\leadsto T_{Q}^{M}}\big)\\
{\color{greenunder}\text{identity law of }\text{frun}_{P}:}\quad & =\text{id}\quad.
\end{align*}
To verify the composition law of lifting, apply $\text{frun}_{R}$
to a composition of two monad morphisms $\phi:L\leadsto M$ and $\chi:M\leadsto N$,
\begin{align*}
\text{frun}_{R}\left(\phi\bef\chi\right) & =\text{frun}_{P}\gunderline{(\text{frun}_{Q}(\phi\bef\chi))}\\
{\color{greenunder}\text{composition law of }\text{frun}_{Q}:}\quad & =\gunderline{\text{frun}_{P}}(\text{frun}_{Q}(\phi)\bef\text{frun}_{Q}(\chi))\\
{\color{greenunder}\text{composition law of }\text{frun}_{P}:}\quad & =\gunderline{\text{frun}_{P}(\text{frun}_{Q}(\phi))}\bef\gunderline{\text{frun}_{P}(\text{frun}_{Q}(\phi))}\\
{\color{greenunder}\text{definition of }\text{frun}_{R}:}\quad & =\text{frun}_{R}(\phi)\bef\text{frun}_{R}(\chi)\quad.
\end{align*}


\paragraph{Base runner law}

We need to show that for any monad morphism $\theta:T_{P}^{Q}\leadsto\text{Id}$
and for any monad $M$, there exists a monad morphism $\text{brun}_{R}(\theta):T_{P}^{T_{Q}^{M}}\leadsto M$.
To define this morphism for a given $\theta$, we will need to use
the base runners for $T_{P}$ and $T_{Q}$. The base runner for $T_{Q}$
has the type signature
\[
\text{brun}_{Q}:\left(Q\leadsto\text{Id}\right)\rightarrow(T_{Q}^{M}\leadsto M)\quad.
\]
We can apply the base runner for $T_{P}$ with the foreign monad $T_{Q}^{M}$,
\[
\text{brun}_{P}:\left(P\leadsto\text{Id}\right)\rightarrow\big(T_{P}^{T_{Q}^{M}}\leadsto T_{Q}^{M}\big)\quad.
\]
It is now clear that we could obtain a monad morphism $T_{P}^{T_{Q}^{M}}\leadsto M$
if we had some monad morphisms $\phi:P\leadsto\text{Id}$ and $\chi:Q\leadsto\text{Id}$,
\[
\text{brun}_{P}(\phi)\bef\text{brun}_{Q}(\chi):T_{P}^{T_{Q}^{M}}\leadsto M\quad.
\]
However, we are only given a single monad morphism $\theta:T_{P}^{Q}\leadsto\text{Id}$.
How can we compute $\phi$ and $\chi$ out of $\theta$? We can use
the liftings $\text{blift}_{P}:P\leadsto T_{P}^{Q}$ and $\text{flift}_{P}:Q\leadsto T_{P}^{Q}$,
which are both monad morphisms, and compose them with $\theta$:
\[
\left(\text{blift}_{P}\bef\theta\right):P\leadsto\text{Id}\quad;\quad\quad\left(\text{flift}_{P}\bef\theta\right):Q\leadsto\text{Id}\quad.
\]
So we can define the monad morphism $\text{brun}_{R}(\theta)$ as
\begin{align*}
\text{brun}_{R}(\theta) & :T_{P}^{T_{Q}^{M}}\leadsto M\quad,\\
\text{brun}_{R}(\theta) & \triangleq\text{brun}_{P}\left(\text{blift}_{P}\bef\theta\right)\bef\text{brun}_{Q}\left(\text{flift}_{P}\bef\theta\right)\quad.
\end{align*}
Since we have defined $\text{brun}_{R}(\theta)$ as a composition
of monad morphisms, $\text{brun}_{R}(\theta)$ is itself a monad morphism
by Statement~\ref{subsec:Statement-monadic-morphism-composition}.

To verify the non-degeneracy law of the base runner, $\text{flift}_{R}\bef\text{brun}_{R}(\theta)=\text{id}$,
we need to use the non-degeneracy laws for the base runners of $T_{P}$
and $T_{Q}$, which are 
\[
\text{flift}_{P}\bef\text{brun}_{P}(\chi^{:P\leadsto\text{Id}})=\text{id}\quad,\quad\quad\text{flift}_{Q}\bef\text{brun}_{Q}(\psi^{:Q\leadsto\text{Id}})=\text{id}\quad.
\]
Then we can write:
\begin{align*}
 & \gunderline{\text{flift}_{R}}\bef\gunderline{\text{brun}_{R}(\theta)}\\
{\color{greenunder}\text{expand definitions}:}\quad & =\text{flift}_{Q}\bef\gunderline{\text{flift}_{P}\bef\text{brun}_{P}\left(\text{blift}_{P}\bef\theta\right)}\bef\text{brun}_{Q}\left(\text{flift}_{P}\bef\theta\right)\\
{\color{greenunder}\text{non-degeneracy law of }\text{brun}_{P}:}\quad & =\gunderline{\text{flift}_{Q}\bef\text{brun}_{Q}\left(\text{flift}_{P}\bef\theta\right)}\\
{\color{greenunder}\text{non-degeneracy law of }\text{brun}_{Q}:}\quad & =\text{id}\quad.
\end{align*}


\paragraph{Monadic naturality laws}

The monadic naturality law of $\text{flift}_{R}$ is
\[
\text{flift}_{R}\bef\text{frun}_{R}(\phi)=\phi\bef\text{flift}_{R}\quad.
\]
We have defined $\text{flift}_{R}\triangleq\text{flift}_{Q}\bef\text{flift}_{P}$,
and we may assume that the monadic naturality laws hold for $\text{flift}_{P}$
and $\text{flift}_{Q}$. A composition of natural transformations
is again a natural transformation; this holds for any category, including
the category of monads. We can also verify this law directly:
\begin{align*}
{\color{greenunder}\text{expect to equal }\phi\bef\text{flift}_{R}:}\quad & \text{flift}_{R}\bef\text{frun}_{R}(\phi)=\text{flift}_{Q}\bef\gunderline{\text{flift}_{P}\bef\text{frun}_{P}}(\text{frun}_{Q}(\phi))\\
{\color{greenunder}\text{monadic naturality of }\text{flift}_{P}:}\quad & =\gunderline{\text{flift}_{Q}\bef\text{frun}_{Q}(\phi)}\bef\text{flift}_{P}\\
{\color{greenunder}\text{monadic naturality of }\text{flift}_{Q}:}\quad & =\phi\bef\text{flift}_{Q}\bef\text{flift}_{P}=\phi\bef\text{flift}_{R}\quad.
\end{align*}
The monadic naturality of $\text{brun}_{R}$ is verified similarly,
assuming the same law for $\text{brun}_{P}$ and $\text{brun}_{Q}$:
\begin{align*}
{\color{greenunder}\text{expect }\text{brun}_{R}(\theta)\bef\phi:}\quad & \text{frun}_{R}(\phi)\bef\text{brun}_{R}(\theta)=\gunderline{\text{frun}_{P}(\text{frun}_{Q}(\phi))\bef\text{brun}_{P}}\left(\text{blift}_{P}\bef\theta\right)\bef\text{brun}_{Q}\left(\text{flift}_{P}\bef\theta\right)\\
{\color{greenunder}\text{same law for }\text{brun}_{P}:}\quad & =\text{brun}_{P}\left(\text{blift}_{P}\bef\theta\right)\bef\gunderline{\text{frun}_{Q}(\phi)\bef\text{brun}_{Q}}\left(\text{flift}_{P}\bef\theta\right)\\
{\color{greenunder}\text{same law for }\text{brun}_{Q}:}\quad & =\text{brun}_{P}\left(\text{blift}_{P}\bef\theta\right)\bef\text{brun}_{Q}\left(\text{flift}_{P}\bef\theta\right)\bef\phi=\text{brun}_{R}(\theta)\bef\phi\quad.
\end{align*}
 

\subsection{Stacking any number of monads. Proofs\label{subsec:Stacking-any-number-of-monads}}

If the monad transformer for $T_{P}^{Q}$ is applied to another monad
$K$, we obtain a new monad $S$:
\[
S^{A}\triangleq T_{P}^{T_{Q}^{K},A}=(P\varangle Q\varangle K)^{A}.
\]
What is the monad transformer $T_{S}$ for the monad $S$? Assuming
that the monad transformer $T_{K}$ is known, we may stack the monads
one level higher:
\[
T_{S}^{M,A}\triangleq T_{P}^{T_{Q}^{T_{K}^{M}},A}=(P\varangle Q\varangle K\varangle M)^{A}\quad.
\]
The result is a stack of four monads $P$, $Q$, $K$, and $M$. Note
that the type parameter $A$ is used as $T_{P}^{(...),A}$, that is,
it belongs to the \emph{outer} transformer $T_{P}^{...,A}$.

We can now define a transformer stack for any number of monads $P$,
$Q$, ..., $Z$ in a similar way:
\begin{equation}
T_{S}^{M,A}\triangleq T_{P}^{T_{Q}^{\iddots^{T_{Z}^{M}}},A}=(P\varangle Q\varangle...\varangle Z\varangle M)^{A}\quad.\label{eq:general-transformer-stack}
\end{equation}
The type parameter $A$ will always remain at the outer transformer
level, while the foreign monad $M$ will be in the innermost nested
position.

It turns out that $T_{S}$ is a lawful monad transformer for \emph{any}
number of stacked monads. We can prove this by induction on the number
of monads. In the previous section, we have proved the transformer
laws for any \emph{three} stacked monads. Now we need to prove the
same laws for a general transformer stack, such as that in Eq.~(\ref{eq:general-transformer-stack}).
Let us temporarily denote by $J$ the monad 
\[
J\triangleq T_{Q}^{\iddots^{T_{Z}^{\text{Id}}}}=Q\varangle...\varangle Z\varangle\text{Id}\cong Q\varangle...\varangle Z\quad,
\]
where we used the identity monad $\text{Id}$ in the place normally
taken by a foreign monad $M$. The monad $J$ is a shorter transformer
stack than $S$, so the inductive assumption tells us that the transformer
laws already hold for the transformer $T_{J}$ defined as
\[
T_{J}^{M}\triangleq T_{Q}^{\iddots^{T_{Z}^{M}}}=\left(Q\varangle...\varangle Z\right)\varangle M\quad.
\]
Since both $T_{P}$ and $T_{J}$ are lawful transformers, their stacking
composition $T_{P}^{T_{J}^{\bullet}}$ is also a lawful transformer
(this was shown in the Section~\ref{subsec:Stacking-two-monads}).
In our notation, $T_{S}^{M,A}=T_{P}^{T_{J}^{M},A}$, and so we have
shown that $T_{S}$ is a lawful transformer.

\section{Common properties of compositional transformers \label{sec:Monad-transformers-that-use-composition}}

We have seen examples of monad transformers built via functor composition,
either as composed-inside or as composed-outside. The simplest examples
are the \lstinline!OptionT! transformer,
\[
L^{A}\triangleq\bbnum 1+A,\quad\quad T_{L}^{M,A}\triangleq M^{L^{A}}=M^{\bbnum 1+A}\quad,
\]
which puts the base monad $L$ \emph{inside} the monad $M$, and the
\lstinline!ReaderT! transformer, 
\[
L^{A}\triangleq R\rightarrow A,\quad\quad T_{L}^{M,A}\triangleq L^{M^{A}}=R\rightarrow M^{A}\quad,
\]
which puts the base monad $L$ \emph{outside} the foreign monad $M$. 

We can prove many properties of both kinds of monad transformers via
a single derivation if we temporarily drop the distinction between
the base monad and the foreign monad. We simply assume that two different
monads, $L$ and $M$, have a functor composition $T^{\bullet}\triangleq L^{M^{\bullet}}$
that also happens to be a monad. Since the assumptions on the monads
$L$ and $M$ are the same, the resulting properties of the composed
monad $T$ will apply equally to both kinds of monad transformers.

To interpret the results, we will assume that $L$ is the base monad
for the composed-outside transformers, and that $M$ is the base monad
for the composed-inside transformers. For instance, we will be able
to prove the laws of liftings $L\leadsto T$ and $M\leadsto T$ regardless
of the choice of the base monad.

What properties of monad transformers will \emph{not} be derivable
in this way? Monad transformers depend on the structure on the base
monad, but not on the structure of the foreign monad; the transformer\textsf{'}s
methods \lstinline!pure! and \lstinline!flatten! are parametric
in the foreign monad. This is expressed via the monad transformer
laws for the runners \lstinline!frun! and \lstinline!brun!, which
we will need to derive separately for each of the two kinds of transformers.

\subsection{Motivation for the \texttt{swap} function}

The first task is to verify the monad laws; that is, to show that
$T^{\bullet}\triangleq L^{M^{\bullet}}$ is a lawful monad. For that,
we need to define the methods for the monad $T$, namely \lstinline!pure!
(short notation \textsf{``}$\text{pu}_{T}$\textsf{''}) and \texttt{}\lstinline!flatten!
(short notation \textsf{``}$\text{ftn}_{T}$\textsf{''}), with the type signatures
\[
\text{pu}_{T}:A\rightarrow L^{M^{A}}\quad,\quad\quad\text{ftn}_{T}:L^{M^{L^{M^{A}}}}\rightarrow L^{M^{A}}\quad.
\]
How can we implement these methods? \emph{All we know} about $L$
and $M$ is that they are monads with their own methods $\text{pu}_{L}$,
$\text{ftn}_{L}$, $\text{pu}_{M}$, and $\text{ftn}_{M}$. We can
easily implement $\text{pu}_{T}$:

\begin{wrapfigure}{l}{0.25\columnwidth}%
\vspace{-1.75\baselineskip}

\[
\xymatrix{\xyScaleY{1.4pc}\xyScaleX{3pc}A\ar[r]\sp(0.5){\text{pu}_{M}}\ar[rd]\sb(0.45){\text{pu}_{T}\triangleq} & M^{A}\ar[d]\sp(0.45){\text{pu}_{L}}\\
 & L^{M^{A}}
}
\]
\vspace{-0.75\baselineskip}
\end{wrapfigure}%
 

~\vspace{-0.25\baselineskip}
\begin{equation}
\text{pu}_{T}\triangleq\text{pu}_{M}\bef\text{pu}_{L}\quad.\label{eq:def-of-pure-T}
\end{equation}
It remains to implement $\text{ftn}_{T}$. In the type $L^{M^{L^{M^{A}}}}$,
we have two layers of the functor $L$ and two layers of the functor
$M$. We could use the available method $\text{ftn}_{L}$ to flatten
the two layers of $L$ if we could \emph{somehow} bring these nested
layers together. However, these layers are separated by a layer of
the functor $M$. To show this layered structure in an easier way,
let us use another notation for the functor composition, 
\[
(L\circ M)^{A}\triangleq L^{M^{A}}\quad.
\]
In this notation, the type signature for \texttt{}\lstinline!flatten!
is written as
\[
\text{ftn}_{T}:L\circ M\circ L\circ M\leadsto L\circ M\quad.
\]
If we had $L\circ L\circ M\circ M$ here, we would have applied $\text{ftn}_{L}$
and flattened the two layers of the functor $L$. Then we would have
flattened the remaining two layers of the functor $M$. How can we
proceed with $L\circ M\circ L\circ M$? The trick is to assume that
we have a function called \lstinline!swap! (short notation \textsf{``}$\text{sw}$\textsf{''}),
which will interchange the order of the layers. The type signature
of \lstinline!swap! is
\[
\text{sw}:M\circ L\leadsto L\circ M\quad,\quad\text{or more verbosely:}\quad\quad\text{sw}_{L,M}^{A}:M^{L^{A}}\rightarrow L^{M^{A}}\quad.
\]
If the \lstinline!swap! operation were \emph{somehow} defined for
the two monads $L$ and $M$, we could implement $\text{ftn}_{T}$
by first swapping the order of the inner layers $M$ and $L$ as 
\[
\text{sw}_{L,M}^{\uparrow L}:L\circ M\circ L\circ M\leadsto L\circ L\circ M\circ M\quad,
\]
and then applying the \texttt{}\lstinline!flatten! methods of the
monads $L$ and $M$. The resulting code for the function $\text{ftn}_{T}$
and the corresponding type diagram are:%
\begin{comment}
precarious formatting
\end{comment}

\begin{wrapfigure}{i}{0.4\columnwidth}%
\vspace{-2.5\baselineskip}

\begin{centering}
\[
\xymatrix{\xyScaleY{1.2pc}\xyScaleX{2.5pc}L^{M^{L^{M^{A}}}}\ar[r]\sp(0.5){\text{sw}^{\uparrow L}}\ar[rrd]\sb(0.5){\text{ftn}_{T}\triangleq} & L^{L^{M^{M^{A}}}}\ar[r]\sp(0.5){\text{ftn}_{L}} & L^{M^{M^{A}}}\ar[d]\sp(0.4){\text{ftn}_{M}^{\uparrow L}}\\
 &  & L^{M^{A}}
}
\]
\par\end{centering}
\vspace{-0.25\baselineskip}
\end{wrapfigure}%

~\vspace{-0.35\baselineskip}
\begin{equation}
\text{ftn}_{T}\triangleq\text{sw}^{\uparrow L}\bef\text{ftn}_{L}\bef\text{ftn}_{M}^{\uparrow L}\quad.\label{eq:define-flatten-via-swap}
\end{equation}

\noindent In this way, the new monad\textsf{'}s \texttt{}\lstinline!flatten!
method can be defined through the \texttt{}\lstinline!swap! operation
in \emph{both} cases (the composed-inside and the composed-outside
transformers). For the two kinds of transformers, the required type
signatures of those functions are:
\begin{align*}
\text{composed-inside}:\quad\text{ftn}_{T}:M^{L^{M^{L^{A}}}}\rightarrow M^{L^{A}}\quad, & \quad\text{sw}_{M,L}^{A}:L^{M^{A}}\rightarrow M^{L^{A}}\quad,\\
\text{composed-outside}:\quad\text{ftn}_{T}:L^{M^{L^{M^{A}}}}\rightarrow L^{M^{A}}\quad, & \quad\text{sw}_{L,M}^{A}:M^{L^{A}}\rightarrow L^{M^{A}}\quad.
\end{align*}


\paragraph{The difference between \texttt{swap} and \texttt{sequence}}

There is a certain similarity between the \texttt{}\lstinline!swap!
operation introduced here and the \lstinline!sequence! operation
introduced in Chapter~\ref{chap:9-Traversable-functors-and} for
traversable functors. Indeed, the type signature of \lstinline!sequence!
is 
\[
\text{seq}:L^{F^{A}}\rightarrow F^{L^{A}}\quad,
\]
where $L$ is a traversable functor and $F$ is an arbitrary applicative
functor (which could be $M$, since all monads are also applicative
functors). However, the similarity ends here. If we wish $M\circ L$
to be a monad, the \texttt{}\lstinline!swap! operation must obey
special laws (to be derived next) that are quite different from the
laws of traversable functors. In particular, it is not true that $M\circ L$
is a monad whenever the monad $L$ is a traversable functor. A counterexample
is found with $L^{A}\triangleq A\times A$ and $M^{A}\triangleq\bbnum 1+A$.
Both monads $L$ and $M$ are traversable (since they are polynomial
functors), but their functor composition $Q^{A}\triangleq\bbnum 1+A\times A$
is not a monad (see Exercise~\ref{subsec:Exercise-1-monads-7}).

Another difference between \lstinline!swap! and \lstinline!sequence!
is that the \texttt{}\lstinline!swap! operation needs to be parametric
in the foreign monad (which may be either $L$ or $M$ according to
the type of the monad transformer), whereas \lstinline!sequence!
is always parametric in the applicative functor $F$. %
\begin{comment}
\emph{This is actually confusing! Let\textsf{'}s not do this and always write
$\text{sw}_{L}^{M}:M^{L^{A}}\rightarrow L^{M^{A}}$}

To denote more clearly the monad with respect to which \lstinline!swap!
is generic, we may write
\begin{align*}
\text{sw}_{L}^{M}:L^{M^{A}}\rightarrow M^{L^{A}}\quad & \text{for the composed-inside transformers,}\\
\text{sw}_{L}^{M}:M^{L^{A}}\rightarrow L^{M^{A}}\quad & \text{for the composed-outside transformers.}
\end{align*}
The superscript $M$ in $\text{sw}_{L}^{M}$ shows that $M$ is a
\emph{type parameter} in \lstinline!swap!; that is, \lstinline!swap!
is generic in the monad $M$. The subscript $L$ in $\text{sw}_{L}^{M}$
shows that the implementations of \lstinline!swap! may need to use
completely different code for different monads $L$.
\end{comment}

To avoid confusion, we call the function $\text{sw}_{L,M}:M^{L^{\bullet}}\leadsto L^{M^{\bullet}}$
\textsf{``}swap\textsf{''} rather than \textsf{``}sequence\textsf{''}. Let us now find out what laws
are required for the \texttt{}\lstinline!swap! operation.\footnote{The \lstinline!swap! operation was studied in the paper \textsf{``}\emph{Composing
monads}\textsf{''}: \texttt{\href{http://web.cecs.pdx.edu/~mpj/pubs/RR-1004.pdf}{http://web.cecs.pdx.edu/$\sim$mpj/pubs/RR-1004.pdf}}}

\subsection{Deriving the necessary laws for \texttt{swap}}

The first law is that \texttt{}\lstinline!swap! must be a natural
transformation. Since \texttt{}\lstinline!swap! has only one type
parameter, there is one naturality law: for any function $f:A\rightarrow B$,

\begin{wrapfigure}{l}{0.35\columnwidth}%
\vspace{-1\baselineskip}

\[
\xymatrix{\xyScaleY{1.5pc}\xyScaleX{2.5pc}M^{L^{A}}\ar[r]\sp(0.5){f^{\uparrow L\uparrow M}}\ar[d]\sb(0.45){\text{sw}} & M^{L^{B}}\ar[d]\sp(0.45){\text{sw}}\\
L^{M^{A}}\ar[r]\sp(0.5){f^{\uparrow M\uparrow L}} & L^{M^{B}}
}
\]

\vspace{-0.25\baselineskip}
\end{wrapfigure}%

~\vspace{-0.35\baselineskip}
\begin{equation}
f^{\uparrow L\uparrow M}\bef\text{sw}_{L,M}=\text{sw}_{L,M}\bef f^{\uparrow M\uparrow L}\quad.\label{eq:swap-law-0-naturality}
\end{equation}

\noindent To derive further laws for \lstinline!swap!, consider the
requirement that the transformed monad $T$ should satisfy the monad
laws:
\begin{align*}
\text{pu}_{T}\bef\text{ftn}_{T}=\text{id}\quad, & \quad\quad\text{pu}_{T}^{\uparrow T}\bef\text{ftn}_{T}=\text{id}\quad,\\
\text{ftn}_{T}^{\uparrow T}\bef\text{ftn}_{T} & =\text{ftn}_{T}\bef\text{ftn}_{T}\quad.
\end{align*}
We will now discover the laws for \texttt{swap} that make the laws
for $\text{ftn}_{T}$ hold automatically, as long as $\text{ftn}_{T}$
is derived from \texttt{}\lstinline!swap! using Eq.~(\ref{eq:define-flatten-via-swap}).

We substitute Eq.~(\ref{eq:define-flatten-via-swap}) into the left
identity law for $\text{ftn}_{T}$ and simplify:
\begin{align}
{\color{greenunder}\text{expect to equal }\text{id}:}\quad & \text{pu}_{T}\bef\gunderline{\text{ftn}_{T}}\nonumber \\
{\color{greenunder}\text{replace }\text{ftn}_{T}\text{ using Eq.~(\ref{eq:define-flatten-via-swap})}:}\quad & =\text{pu}_{T}\bef\text{sw}^{\uparrow L}\bef\text{ftn}_{L}\bef\text{ftn}_{M}^{\uparrow L}\nonumber \\
{\color{greenunder}\text{replace }\text{pu}_{T}\text{ using Eq.~(\ref{eq:def-of-pure-T})}:}\quad & =\text{pu}_{M}\bef\gunderline{\text{pu}_{L}\bef\text{sw}^{\uparrow L}}\bef\text{ftn}_{L}\bef\text{ftn}_{M}^{\uparrow L}\nonumber \\
{\color{greenunder}\text{naturality law of }\text{pu}_{L}:}\quad & =\text{pu}_{M}\bef\text{sw}\bef\gunderline{\text{pu}_{L}\bef\text{ftn}_{L}}\bef\text{ftn}_{M}^{\uparrow L}\nonumber \\
{\color{greenunder}\text{left identity law for }L:}\quad & =\text{pu}_{M}\bef\text{sw}\bef\text{ftn}_{M}^{\uparrow L}\quad.\label{eq:left-identity-ftn-T}
\end{align}
How could the last expression in Eq.~(\ref{eq:left-identity-ftn-T})
be equal to \lstinline!identity!? We know nothing about the \texttt{}\lstinline!pure!
and \texttt{}\lstinline!flatten! methods of the monads $L$ and
$M$, except that these methods obey the monad laws. We could satisfy
Eq.~(\ref{eq:left-identity-ftn-T}) if we somehow reduce that expression
to
\[
\text{pu}_{M}^{\uparrow L}\bef\text{ftn}_{M}^{\uparrow L}=\left(\text{pu}_{M}\bef\text{ftn}_{M}\right)^{\uparrow L}=\text{id}\quad.
\]
This will be possible only if we are able to interchange the order
of function compositions with \lstinline!swap! and eliminate \lstinline!swap!
from the expression. So, we must require the \textsf{``}outer identity law\textsf{''}
for \lstinline!swap!:

\begin{wrapfigure}{l}{0.3\columnwidth}%
\vspace{-1\baselineskip}

\[
\xymatrix{\xyScaleY{1pc}\xyScaleX{2.5pc}L^{A}\ar[r]\sp(0.5){\text{pu}_{M}}\ar[rd]\sb(0.4){\text{pu}_{M}^{\uparrow L}} & M^{L^{A}}\ar[d]\sp(0.4){\text{sw}}\\
 & L^{M^{A}}
}
\]

\vspace{-0.25\baselineskip}
\end{wrapfigure}%

~\vspace{-0.35\baselineskip}
\begin{equation}
\text{pu}_{M}\bef\text{sw}=\text{pu}_{M}^{\uparrow L}\quad.\label{eq:swap-law-1-M-identity}
\end{equation}
Intuitively, this law says that a pure layer of the monad $M$ remains
pure after interchanging the order of layers with \lstinline!swap!.

With this law, we can finish the derivation in Eq.~(\ref{eq:left-identity-ftn-T}):
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{id}:}\quad & \text{pu}_{M}\bef\text{sw}\bef\text{ftn}_{M}^{\uparrow L}\\
{\color{greenunder}\text{outer identity law of }\text{sw}:}\quad & =\text{pu}_{M}^{\uparrow L}\bef\text{ftn}_{M}^{\uparrow L}=(\gunderline{\text{pu}_{M}\bef\text{ftn}_{M}})^{\uparrow L}=\text{id}^{\uparrow L}=\text{id}\quad.
\end{align*}
So, the $M$-identity law for \texttt{swap} entails the left identity
law for $T$.

In the same way, we motivate the \textsf{``}inner identity\textsf{''} law for \texttt{swap}:

\begin{wrapfigure}{l}{0.3\columnwidth}%
\vspace{-1.25\baselineskip}

\[
\xymatrix{\xyScaleY{1pc}\xyScaleX{2.5pc}M^{A}\ar[r]\sp(0.5){\text{pu}_{L}^{\uparrow M}}\ar[rd]\sb(0.45){\text{pu}_{L}} & M^{L^{A}}\ar[d]\sp(0.4){\text{sw}}\\
 & L^{M^{A}}
}
\]

\vspace{-0.25\baselineskip}
\end{wrapfigure}%

~\vspace{-0.35\baselineskip}
\begin{equation}
\text{pu}_{L}^{\uparrow M}\bef\text{sw}=\text{pu}_{L}\quad.\label{eq:swap-law-2-L-identity}
\end{equation}
This law requires that a \textsf{``}pure\textsf{''} layer of the functor $L$ should
remain \textsf{``}pure\textsf{''} after swapping the order of layers.

Assuming this law, we can derive the right identity law for $T$:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{id}:}\quad & \text{pu}_{T}^{\uparrow T}\bef\text{ftn}_{T}\\
{\color{greenunder}\text{by definition, }f^{\uparrow T}\triangleq f^{\uparrow M\uparrow L}:}\quad & =(\text{pu}_{T})^{\uparrow M\uparrow L}\bef\text{ftn}_{T}\\
{\color{greenunder}\text{definitions of }\text{pu}_{T}\text{ and }\text{ftn}_{T}:}\quad & =\text{pu}_{M}^{\uparrow M\uparrow L}\bef\gunderline{\text{pu}_{L}^{\uparrow M\uparrow L}\bef\text{sw}^{\uparrow L}}\bef\text{ftn}_{L}\bef\text{ftn}_{M}^{\uparrow L}\\
{\color{greenunder}\text{inner identity law of }\text{sw},\text{ under }^{\uparrow L}:}\quad & =\text{pu}_{M}^{\uparrow M\uparrow L}\bef\gunderline{\text{pu}_{L}^{\uparrow L}\bef\text{ftn}_{L}}\bef\text{ftn}_{M}^{\uparrow L}\\
{\color{greenunder}\text{right identity law of }L:}\quad & =\text{pu}_{M}^{\uparrow M\uparrow L}\bef\text{ftn}_{M}^{\uparrow L}=\gunderline{(\text{pu}_{M}^{\uparrow M}\bef\text{ftn}_{M})}^{\uparrow L}=\text{id}^{\uparrow L}=\text{id}\quad.
\end{align*}

Deriving the monad associativity law for $T$,
\[
\text{ftn}_{T}^{\uparrow T}\bef\text{ftn}_{T}=\text{ftn}_{T}\bef\text{ftn}_{T}\quad,
\]
turns out to require \emph{two} further laws of \lstinline!swap!.
Let us see why.

Substituting the definition of $\text{ftn}_{T}$ into the associativity
law, we get
\begin{align}
 & \big(\text{sw}^{\uparrow L}\bef\text{ftn}_{L}\bef\text{ftn}_{M}^{\uparrow L}\big)^{\uparrow M\uparrow L}\bef\text{sw}^{\uparrow L}\bef\text{ftn}_{L}\bef\text{ftn}_{M}^{\uparrow L}\nonumber \\
 & \quad\overset{?}{=}\text{sw}^{\uparrow L}\bef\text{ftn}_{L}\bef\text{ftn}_{M}^{\uparrow L}\bef\text{sw}^{\uparrow L}\bef\text{ftn}_{L}\bef\text{ftn}_{M}^{\uparrow L}\quad.\label{eq:t-assoc-law-expanded}
\end{align}
The only hope of proving this law is being able to interchange $\text{ftn}_{L}$
as well as $\text{ftn}_{M}$ with $\text{sw}$. In other words, the
\texttt{}\lstinline!swap! function should be in some way adapted
to the \texttt{}\lstinline!flatten! methods of both $L$ and $M$.

Let us look for such interchange laws. One possibility is to have
a law involving $\text{ftn}_{M}\bef\text{sw}$, which is a function
of type $M^{M^{L^{A}}}\rightarrow L^{M^{A}}$ or, in equivalent but
shorter notation, $M\circ M\circ L\leadsto L\circ M$. This function
first flattens the two adjacent layers of $M$, obtaining $M\circ L$,
and then swaps the two remaining layers, moving the $L$ layer outside.
Let us think about what law could exist for this kind of transformation.
It is plausible that we may obtain the same result if we first swap
the layers twice, so that the $L$ layer moves to the outside, obtaining
$L\circ M\circ M$, and then flatten the two inner $M$ layers. Writing
this assumption in code, we obtain the \textsf{``}outer interchange\textsf{''} law:%
\begin{comment}
precarious formatting
\end{comment}

\begin{wrapfigure}{i}{0.34\columnwidth}%
\vspace{-2.2\baselineskip}

\begin{centering}
\[
\xymatrix{\xyScaleY{1pc}\xyScaleX{2.5pc} & M^{M^{L^{A}}}\ar[r]\sp(0.5){\text{ftn}_{M}}\ar[ld]\sb(0.45){\text{sw}^{\uparrow M}} & M^{L^{A}}\ar[d]\sb(0.4){\text{sw}}\\
M^{L^{M^{A}}}\ar[r]\sb(0.5){\text{sw}} & L^{M^{M^{A}}}\ar[r]\sb(0.5){\text{ftn}_{M}^{\uparrow L}} & L^{M^{A}}
}
\]
\par\end{centering}
\vspace{-0.2\baselineskip}
\end{wrapfigure}%

~\vspace{-0.2\baselineskip}
\begin{equation}
\text{ftn}_{M}\bef\text{sw}=\text{sw}^{\uparrow M}\bef\text{sw}\bef\text{ftn}_{M}^{\uparrow L}\quad.\label{eq:swap-law-3-M-interchange}
\end{equation}

The analogous \textsf{``}inner interchange\textsf{''} law involving two layers of
$L$ and a transformation $M\circ L\circ L\leadsto L\circ M$ is written
as:

\begin{wrapfigure}{i}{0.34\columnwidth}%
\vspace{-2\baselineskip}

\noindent 
\[
\xymatrix{\xyScaleY{1pc}\xyScaleX{2.5pc} & M^{L^{L^{A}}}\ar[r]\sp(0.5){\text{ftn}_{L}^{\uparrow M}}\ar[ld]\sb(0.45){\text{sw}} & M^{L^{A}}\ar[d]\sb(0.4){\text{sw}}\\
L^{M^{L^{A}}}\ar[r]\sb(0.5){\text{sw}^{\uparrow L}} & L^{L^{M^{A}}}\ar[r]\sb(0.5){\text{ftn}_{L}} & L^{M^{A}}
}
\]

\vspace{-0.45\baselineskip}
\end{wrapfigure}%

~\vspace{-0.2\baselineskip}
\begin{equation}
\text{ftn}_{L}^{\uparrow M}\bef\text{sw}=\text{sw}\bef\text{sw}^{\uparrow L}\bef\text{ftn}_{L}\quad.\label{eq:swap-law-4-L-interchange}
\end{equation}

At this point, we have simply written down two plausible laws, hoping
that they will help us derive the associativity law for $T$. We will
now verify that this is indeed so.

Both sides of the law in Eq.~(\ref{eq:t-assoc-law-expanded}) involve
compositions of several \lstinline!flatten!s and \lstinline!swap!s.
The heuristic idea of the proof is to use various laws to move all
\lstinline!flatten!s to right of the composition, while moving all
\lstinline!swap!s to the left. In this way we will rewrite both sides
of Eq.~(\ref{eq:t-assoc-law-expanded}) to a similar form, hoping
to prove that they are equal.

We begin with the right-hand side of Eq.~(\ref{eq:t-assoc-law-expanded})
since it is simpler than the left-hand side, and look for ways of
using the interchange laws. At every step of the calculation, there
happens to be only one place where some law can be applied:
\begin{align*}
 & \text{sw}^{\uparrow L}\bef\text{ftn}_{L}\bef\gunderline{\text{ftn}_{M}^{\uparrow L}\bef\text{sw}^{\uparrow L}}\bef\text{ftn}_{L}\bef\text{ftn}_{M}^{\uparrow L}\\
{\color{greenunder}\text{composition for }L:}\quad & =\text{sw}^{\uparrow L}\bef\text{ftn}_{L}\bef\gunderline{(\text{ftn}_{M}\bef\text{sw})}^{\uparrow L}\bef\text{ftn}_{L}\bef\text{ftn}_{M}^{\uparrow L}\\
{\color{greenunder}\text{outer interchange law of }\text{sw}:}\quad & =\text{sw}^{\uparrow L}\bef\text{ftn}_{L}\bef\gunderline{(\text{sw}^{\uparrow M}\bef\text{sw}\bef\text{ftn}_{M}^{\uparrow L})}^{\uparrow L}\bef\text{ftn}_{L}\bef\text{ftn}_{M}^{\uparrow L}\\
{\color{greenunder}\text{composition under }^{\uparrow L}:}\quad & =\text{sw}^{\uparrow L}\bef\text{ftn}_{L}\bef\gunderline{\text{sw}^{\uparrow M\uparrow L}\bef\text{sw}^{\uparrow L}}\bef\gunderline{\text{ftn}_{M}^{\uparrow L\uparrow L}\bef\text{ftn}_{L}}\bef\text{ftn}_{M}^{\uparrow L}\\
{\color{greenunder}\text{naturality law of }\text{ftn}_{L}:}\quad & =\text{sw}^{\uparrow L}\bef\gunderline{\text{ftn}_{L}\bef(\text{sw}^{\uparrow M}\bef\text{sw})^{\uparrow L}}\bef\text{ftn}_{L}\bef\text{ftn}_{M}^{\uparrow L}\bef\text{ftn}_{M}^{\uparrow L}\\
{\color{greenunder}\text{naturality law of }\text{ftn}_{L}:}\quad & =\text{sw}^{\uparrow L}\bef\gunderline{(\text{sw}^{\uparrow M}\bef\text{sw})^{\uparrow L\uparrow L}\bef\text{ftn}_{L}}\bef\text{ftn}_{L}\bef\text{ftn}_{M}^{\uparrow L}\bef\text{ftn}_{M}^{\uparrow L}\quad.
\end{align*}
Now all \lstinline!swap!s are on the left and all \lstinline!flatten!s
on the right of the expression.

Transform the right-hand side of Eq.~(\ref{eq:t-assoc-law-expanded})
in the same way as
\begin{align*}
 & \big(\text{sw}^{\uparrow L}\bef\text{ftn}_{L}\bef\gunderline{\text{ftn}_{M}^{\uparrow L}}\big)^{\uparrow M\uparrow L}\gunderline{\bef\text{sw}^{\uparrow L}}\bef\text{ftn}_{L}\bef\text{ftn}_{M}^{\uparrow L}\\
{\color{greenunder}\text{functor composition}:}\quad & =(\text{sw}^{\uparrow L}\bef\text{ftn}_{L})^{\uparrow M\uparrow L}\bef\gunderline{(\text{ftn}_{M}^{\uparrow L\uparrow M}\bef\text{sw})}^{\uparrow L}\bef\text{ftn}_{L}\bef\text{ftn}_{M}^{\uparrow L}\\
{\color{greenunder}\text{naturality law of }\text{sw}:}\quad & =(\text{sw}^{\uparrow L}\bef\text{ftn}_{L})^{\uparrow M\uparrow L}\bef\big(\text{sw}\bef\gunderline{\text{ftn}_{M}^{\uparrow M\uparrow L}}\big)^{\uparrow L}\gunderline{\bef\text{ftn}_{L}}\bef\text{ftn}_{M}^{\uparrow L}\\
{\color{greenunder}\text{naturality law of }\text{ftn}_{L}:}\quad & =\text{sw}^{\uparrow L\uparrow M\uparrow L}\bef\text{ftn}_{L}^{\uparrow M\uparrow L}\bef\text{sw}^{\uparrow L}\bef\text{ftn}_{L}\bef\gunderline{\text{ftn}_{M}^{\uparrow M\uparrow L}\bef\text{ftn}_{M}^{\uparrow L}}\\
{\color{greenunder}\text{associativity of }\text{ftn}_{M}:}\quad & =\text{sw}^{\uparrow L\uparrow M\uparrow L}\bef\gunderline{(\text{ftn}_{L}^{\uparrow M}\bef\text{sw})}^{\uparrow L}\bef\text{ftn}_{L}\bef\text{ftn}_{M}^{\uparrow L}\bef\text{ftn}_{M}^{\uparrow L}\\
{\color{greenunder}\text{inner interchange law of }\text{sw}:}\quad & =\text{sw}^{\uparrow L\uparrow M\uparrow L}\bef\big(\text{sw}\bef\text{sw}^{\uparrow L}\bef\gunderline{\text{ftn}_{L}}\big)^{\uparrow L}\gunderline{\bef\text{ftn}_{L}}\bef\text{ftn}_{M}^{\uparrow L}\bef\text{ftn}_{M}^{\uparrow L}\\
{\color{greenunder}\text{associativity law of }\text{ftn}_{L}:}\quad & =\big(\text{sw}^{\uparrow L\uparrow M}\bef\text{sw}\bef\text{sw}^{\uparrow L}\big)^{\uparrow L}\bef\gunderline{\text{ftn}_{L}\bef\text{ftn}_{L}}\bef\text{ftn}_{M}^{\uparrow L}\bef\text{ftn}_{M}^{\uparrow L}\quad.
\end{align*}
We have again managed to move all \lstinline!swap!s to the left and
all \lstinline!flatten!s to the right of the expression. 

Comparing now the two sides of the associativity law, we see that
all the \lstinline!flatten!s occur in the same combination: $\text{ftn}_{L}\bef\text{ftn}_{L}\bef\text{ftn}_{M}^{\uparrow L}\bef\text{ftn}_{M}^{\uparrow L}$.
It remains to show that 
\[
\text{sw}^{\uparrow L}\bef(\text{sw}^{\uparrow M}\bef\text{sw})^{\uparrow L\uparrow L}\overset{?}{=}(\text{sw}^{\uparrow L\uparrow M}\bef\text{sw}\bef\text{sw}^{\uparrow L})^{\uparrow L}\quad,
\]
or equivalently
\[
(\text{sw}\bef\text{sw}^{\uparrow M\uparrow L}\bef\text{sw}^{\uparrow L})^{\uparrow L}\overset{?}{=}(\text{sw}^{\uparrow L\uparrow M}\bef\text{sw}\bef\text{sw}^{\uparrow L})^{\uparrow L}\quad.
\]
The two sides are equal due to the naturality law of \texttt{}\lstinline!swap!,
\[
\text{sw}\bef\text{sw}^{\uparrow M\uparrow L}=\text{sw}^{\uparrow L\uparrow M}\bef\text{sw}.
\]

We have proved the following statement:

\subsubsection{Statement \label{sec:Statement-swap-laws-to-monad-transformer-first-law}\ref{sec:Statement-swap-laws-to-monad-transformer-first-law}}

For two monads $L$ and $M$, assume that there exists a function
\lstinline!swap!,
\[
\text{sw}_{L,M}:M^{L^{A}}\rightarrow L^{M^{A}}\quad,
\]
which is a natural transformation satisfying four additional laws:
\begin{align*}
{\color{greenunder}\text{outer identity}:}\quad & \text{pu}_{L}^{\uparrow M}\bef\text{sw}_{L,M}=\text{pu}_{L}\quad,\\
{\color{greenunder}\text{inner identity}:}\quad & \text{pu}_{M}\bef\text{sw}_{L,M}=\text{pu}_{M}^{\uparrow L}\quad,\\
{\color{greenunder}\text{outer interchange}:}\quad & \text{ftn}_{L}^{\uparrow M}\bef\text{sw}_{L,M}=\text{sw}_{L,M}\bef\text{sw}_{L,M}^{\uparrow L}\bef\text{ftn}_{L}\quad,\\
{\color{greenunder}\text{inner interchange}:}\quad & \text{ftn}_{M}\bef\text{sw}_{L,M}=\text{sw}_{L,M}^{\uparrow M}\bef\text{sw}_{L,M}\bef\text{ftn}_{M}^{\uparrow L}\quad.
\end{align*}
Then the functor composition
\[
T^{A}\triangleq L^{M^{A}}=\left(L\circ M\right)^{A}
\]
is a monad with the methods \lstinline!pure! and \lstinline!flatten!
defined by
\begin{align}
\text{pu}_{T} & \triangleq\text{pu}_{M}\bef\text{pu}_{L}\quad,\label{eq:def-pure-T-via-pure-L-and-pure-M}\\
\text{ftn}_{T} & \triangleq\text{sw}_{L,M}^{\uparrow L}\bef\text{ftn}_{L}\bef\text{ftn}_{M}^{\uparrow L}\quad.\label{eq:def-flatten-T-via-sw-and-flatten-L-M}
\end{align}


\paragraph{Intuition behind \texttt{swap}\textsf{'}s interchange laws}

Those laws guarantee that any functor composition built up from $L$
and $M$, e.g.:
\[
M\circ M\circ L\circ M\circ L\circ L\circ M\circ M\circ L\quad,
\]
can be simplified to a value of type $T^{A}=L^{M^{A}}$ by flattening
the layers using $\text{ftn}_{L}$, $\text{ftn}_{M}$, or $\text{ftn}_{T}$,
or by interchanging the layers with \lstinline!swap!. We may apply
\lstinline!flatten! or \lstinline!swap! in any order, and we will
always get the same final value of type $T^{A}$.

In other words, the monadic effects of the monads $L$ and $M$ can
be arbitrarily interleaved, swapped, and flattened in any order, with
no change to the final results. The programmer is free to refactor
a monadic program, say, by first computing some $L$-effects in a
separate functor block of $L$-\lstinline!flatMap!s and only then
combining the result with the rest of the computation in the monad
$T$. Regardless of the refactoring, the monad $T$ computes all the
effects correctly. This is what programmers would expect of the monad
$T$, if it is to be regarded as a useful monad transformer.

We will now derive the properties of the monad $T$ that follow from
the interchange laws. We will find that it is easier to formulate
these laws in terms of \lstinline!swap! than in terms of $\text{ftn}_{T}$.
In practice, all known examples of compositional monad transformers
(the \lstinline!Writer! monad, the pass/fail monads, and the \textsf{``}rigid\textsf{''}
monads) are defined via a \lstinline!swap! function.

\subsection{Deriving \texttt{swap} from \texttt{flatten}\label{subsec:Deriving-swap-from-flatten}}

We have shown that the \texttt{}\lstinline!flatten! method of the
monad $T^{\bullet}=L^{M^{\bullet}}$ can be defined via the \texttt{}\lstinline!swap!
method. However, we have seen examples of some composable monads (such
as \texttt{}\lstinline!Reader! and \lstinline!Option!) where we
already know the definitions of the \texttt{}\lstinline!flatten!
method for the composed monad $T$. Does a suitable \texttt{}\lstinline!swap!
function exist for these examples? In other words, if a \texttt{}\lstinline!flatten!
function for the monad $T=L\circ M$ is already known, can we find
out whether a \texttt{}\lstinline!swap! function exists such that
the\emph{ given} \texttt{}\lstinline!flatten! function is expressed
via Eq.~(\ref{eq:define-flatten-via-swap})? 

To answer this question, let us look at the type signature of \texttt{}\lstinline!flatten!
for $T$:
\[
\text{ftn}_{T}:L\circ M\circ L\circ M\leadsto L\circ M\quad.
\]
This type signature is different from $\text{sw}:M\circ L\leadsto L\circ M$
in that the argument of $\text{ftn}_{T}$ has extra layers of the
functors $L$ and $M$ outside the $M\circ L$ composition. We can
use the \lstinline!pure! methods of $M$ and $L$ to add such extra
layers to a value of type $M\circ L$, without modifying any monadic
effects present in $M\circ L$. This will allow us to apply $\text{ftn}_{T}$
and to obtain a value of type $L\circ M$. The resulting code for
the function $\text{ftn}_{T}$ and the corresponding type diagram
are:%
\begin{comment}
precarious formatting
\end{comment}

\begin{wrapfigure}{i}{0.42\columnwidth}%
\vspace{-1.8\baselineskip}

\begin{centering}
\[
\xymatrix{\xyScaleY{1.5pc}\xyScaleX{3pc}M^{L^{A}}\ar[r]\sp(0.5){\text{pu}_{M}^{\uparrow L\uparrow M}}\ar[rrd]\sb(0.5){\text{sw}\triangleq} & M^{L^{M^{A}}}\ar[r]\sp(0.5){\text{pu}_{L}} & L^{M^{L^{M^{A}}}}\ar[d]\sb(0.45){\text{ftn}_{T}}\\
 &  & L^{M^{A}}
}
\]
\par\end{centering}
\vspace{-0.15\baselineskip}
\end{wrapfigure}%

~\vspace{-0.35\baselineskip}
\begin{equation}
\text{sw}=\text{pu}_{M}^{\uparrow L\uparrow M}\bef\text{pu}_{L}\bef\text{ftn}_{T}\quad.\label{eq:define-swap-via-flatten}
\end{equation}

We have related $\text{ftn}_{T}$ and $\text{sw}_{L,M}$ to each other.
Are these functions always equivalent? 

\subsubsection{Statement \label{subsec:Statement-swap-equivalence-to-flatten}\ref{subsec:Statement-swap-equivalence-to-flatten}}

The equivalence of \lstinline!flatten! and \lstinline!swap! holds
under the following conditions:

\textbf{(a)} Given an implementation of \lstinline!swap! that obeys
the naturality law, we define $\text{ftn}_{T}$ via Eq.~(\ref{eq:define-flatten-via-swap})
and then substitute that $\text{ftn}_{T}$ into Eq.~(\ref{eq:define-swap-via-flatten})
to define a new \lstinline!swap! function. The new \lstinline!swap!
function will be equal to the \lstinline!swap! function given initially.

\textbf{(b)} Given an implementation of $\text{ftn}_{T}$ satisfying
the \textsf{``}compatibility laws\textsf{''}~(\ref{eq:ftn-first-compatibility-law})\textendash (\ref{eq:ftn-second-compatibility-law}),
we define \lstinline!swap! via Eq.~(\ref{eq:define-swap-via-flatten})
and then substitute that \lstinline!swap! into Eq.~(\ref{eq:define-flatten-via-swap})
to define a new \lstinline!flatten! function. The new \lstinline!flatten!
function will be equal to the $\text{ftn}_{T}$ function given initially.

\subparagraph{Proof}

\textbf{(a)} Substitute $\text{ftn}_{T}$ from Eq.~(\ref{eq:define-flatten-via-swap})
into Eq.~(\ref{eq:define-swap-via-flatten}):
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{sw}:}\quad & \text{pu}_{M}^{\uparrow L\uparrow M}\bef\text{pu}_{L}\bef\gunderline{\text{ftn}_{T}}=\text{pu}_{M}^{\uparrow L\uparrow M}\bef\gunderline{\text{pu}_{L}\bef\text{sw}^{\uparrow L}}\bef\text{ftn}_{L}\bef\text{ftn}_{M}^{\uparrow L}\\
{\color{greenunder}\text{naturality law of }\text{pu}_{L}:}\quad & =\text{pu}_{M}^{\uparrow L\uparrow M}\bef\text{sw}\bef\gunderline{\text{pu}_{L}\bef\text{ftn}_{L}}\bef\text{ftn}_{M}^{\uparrow L}\\
{\color{greenunder}\text{left identity law of }L:}\quad & =\gunderline{\text{pu}_{M}^{\uparrow L\uparrow M}\bef\text{sw}}\bef\text{ftn}_{M}^{\uparrow L}\\
{\color{greenunder}\text{naturality law of }\text{sw}:}\quad & =\text{sw}\bef\gunderline{\text{pu}_{M}^{\uparrow M\uparrow L}\bef\text{ftn}_{M}^{\uparrow L}}=\text{sw}\bef\gunderline{(\text{pu}_{M}^{\uparrow M}\bef\text{ftn}_{M})}^{\uparrow L}=\text{sw}\quad.
\end{align*}
We recovered the initial \lstinline!swap! function.

\textbf{(b)} Substitute \lstinline!swap! from Eq.~(\ref{eq:define-swap-via-flatten})
into Eq.~(\ref{eq:define-flatten-via-swap}):
\begin{align}
 & \gunderline{\text{sw}}^{\uparrow L}\bef\text{ftn}_{L}\bef\text{ftn}_{M}^{\uparrow L}=\gunderline{(\text{pu}_{M}^{\uparrow L\uparrow M}\bef\text{pu}_{L}\bef\text{ftn}_{T})^{\uparrow L}}\bef\text{ftn}_{L}\bef\text{ftn}_{M}^{\uparrow L}\nonumber \\
{\color{greenunder}\text{functor composition }:}\quad & =\text{pu}_{M}^{\uparrow L\uparrow M\uparrow L}\bef\text{pu}_{L}^{\uparrow L}\bef\text{ftn}_{T}^{\uparrow L}\bef\text{ftn}_{L}\bef\text{ftn}_{M}^{\uparrow L}\quad.\label{eq:deriv-sw-from-ftn-a}
\end{align}
At this point, we are stuck: we cannot transform the last expression
into $\text{ftn}_{T}$. Without assuming additional laws, it \emph{does
not follow} that the right-hand side of Eq.~(\ref{eq:deriv-sw-from-ftn-a})
is equal to $\text{ftn}_{T}$. Let us now derive those additional
laws. 

The only sub-expression in Eq.~(\ref{eq:deriv-sw-from-ftn-a}) that
we could possibly transform is the composition $\text{ftn}_{T}^{\uparrow L}\bef\text{ftn}_{L}$.
So, we need to assume a law involving the expression 
\[
(\text{ftn}_{T}^{\uparrow L}\bef\text{ftn}_{L}):L\circ L\circ M\circ L\circ M\leadsto L\circ M\quad.
\]
This function flattens the two layers of $\left(L\circ M\right)$
and then flattens the remaining two layers of $L$. Another function
with the same type signature could first flatten the two \emph{outside}
layers of $L$ and then flatten the two remaining layers of $\left(L\circ M\right)$:
\[
(\text{ftn}_{L}\bef\text{ftn}_{T}):L\circ L\circ M\circ L\circ M\leadsto L\circ M\quad.
\]
So we conjecture that a possibly useful additional law for $\text{ftn}_{T}$
is

\begin{wrapfigure}{l}{0.3\columnwidth}%
\vspace{-1.8\baselineskip}

\[
\xymatrix{\xyScaleY{1.4pc}\xyScaleX{2.5pc}L^{L^{M^{L^{M^{A}}}}}\ar[r]\sp(0.5){\text{ftn}_{L}}\ar[d]\sb(0.45){\text{ftn}_{T}^{\uparrow L}} & L^{M^{L^{M^{A}}}}\ar[d]\sb(0.45){\text{ftn}_{T}}\\
L^{L^{M^{A}}}\ar[r]\sb(0.5){\text{ftn}_{L}} & L^{M^{A}}
}
\]

\vspace{-0.15\baselineskip}
\end{wrapfigure}%

~\vspace{-0.35\baselineskip}
\begin{equation}
\text{ftn}_{L}\bef\text{ftn}_{T}=\text{ftn}_{T}^{\uparrow L}\bef\text{ftn}_{L}\quad.\label{eq:ftn-first-compatibility-law}
\end{equation}
This law expresses a certain kind of \textsf{``}compatibility\textsf{''} between the
monads $L$ and $T$.

With this law, the right-hand side of Eq.~(\ref{eq:deriv-sw-from-ftn-a})
becomes
\begin{align*}
 & \text{pu}_{M}^{\uparrow L\uparrow M\uparrow L}\bef\gunderline{\text{pu}_{L}^{\uparrow L}\bef\text{ftn}_{L}}\bef\text{ftn}_{T}\bef\text{ftn}_{M}^{\uparrow L}\\
{\color{greenunder}\text{right identity law of }L:}\quad & =\text{pu}_{M}^{\uparrow L\uparrow M\uparrow L}\bef\text{ftn}_{T}\bef\text{ftn}_{M}^{\uparrow L}\quad.
\end{align*}
Again, we cannot proceed unless we assume a law involving the expression
\[
\big(\text{ftn}_{T}\bef\text{ftn}_{M}^{\uparrow L}\big):L\circ M\circ L\circ M\circ M\leadsto L\circ M\quad.
\]
This function first flattens the two layers of $\left(L\circ M\right)$
and then flattens the remaining two layers of $M$. An alternative
order of flattenings is to first flatten the \emph{innermost} two
layers of $M$:
\[
\big(\text{ftn}_{M}^{\uparrow L\uparrow M\uparrow L}\bef\text{ftn}_{T}\big):L\circ M\circ L\circ M\circ M\leadsto L\circ M\quad.
\]
The second conjectured law is therefore

\begin{wrapfigure}{l}{0.3\columnwidth}%
\vspace{-1.8\baselineskip}

\[
\xymatrix{\xyScaleY{1.4pc}\xyScaleX{2.5pc}L^{M^{L^{M^{M^{A}}}}}\ar[r]\sp(0.5){\text{ftn}_{T}}\ar[d]\sb(0.5){\text{ftn}_{M}^{\uparrow L\uparrow M\uparrow L}} & L^{M^{M^{A}}}\ar[d]\sb(0.5){\text{ftn}_{M}^{\uparrow L}}\\
L^{M^{L^{M^{A}}}}\ar[r]\sb(0.5){\text{ftn}_{T}} & L^{M^{A}}
}
\]

\vspace{-0.15\baselineskip}
\end{wrapfigure}%

~\vspace{-0.35\baselineskip}
\begin{equation}
\text{ftn}_{T}\bef\text{ftn}_{M}^{\uparrow L}=\text{ftn}_{M}^{\uparrow L\uparrow M\uparrow L}\bef\text{ftn}_{T}\quad.\label{eq:ftn-second-compatibility-law}
\end{equation}
This law expresses a certain kind of \textsf{``}compatibility\textsf{''} between the
monads $M$ and $T$.

Assuming this law, we can finally complete the derivation:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{ftn}_{T}:}\quad & \text{pu}_{M}^{\uparrow L\uparrow M\uparrow L}\bef\text{ftn}_{T}\bef\text{ftn}_{M}^{\uparrow L}\\
{\color{greenunder}\text{substitute the second conjecture}:}\quad & =\gunderline{\text{pu}_{M}^{\uparrow L\uparrow M\uparrow L}\bef\text{ftn}_{M}^{\uparrow L\uparrow M\uparrow L}}\bef\text{ftn}_{T}\\
{\color{greenunder}\text{functor composition }:}\quad & =\gunderline{(\text{pu}_{M}\bef\text{ftn}_{M})}^{\uparrow L\uparrow M\uparrow L}\bef\text{ftn}_{T}\\
{\color{greenunder}\text{left identity law of }M:}\quad & =\text{ftn}_{T}\quad.
\end{align*}
We recovered the initial $\text{ftn}_{T}$ by assuming two additional
laws. $\square$

It turns out that those laws will always hold when $\text{ftn}_{T}$
is defined via \lstinline!swap! (see Exercise~\ref{par:Exercise-1-interchange-laws-for-ftn-T}).

It may be hard to verify directly the monad laws for $L\circ M$ because
of deeply nested type constructors, e.g., $L\circ M\circ L\circ M\circ L\circ M$.
If the monad $L\circ M$ has a \lstinline!swap! method, it is simpler
first to verify the laws of \lstinline!swap! and then to obtain the
monad laws of $L\circ M$ via Statement~\ref{sec:Statement-swap-laws-to-monad-transformer-first-law}.

\subsection{Monad transformer identity law. Proofs}

\subsubsection{Statement \label{subsec:Statement-composition-transformer-identity-law}\ref{subsec:Statement-composition-transformer-identity-law}}

Assume that $\text{pu}_{T}$ and $\text{ftn}_{T}$ are defined by
Eqs.~(\ref{eq:def-pure-T-via-pure-L-and-pure-M})\textendash (\ref{eq:def-flatten-T-via-sw-and-flatten-L-M}),
and that the two identity laws of \lstinline!swap! hold (see Statement~\ref{sec:Statement-swap-laws-to-monad-transformer-first-law}),
\begin{align*}
{\color{greenunder}\text{outer identity law}:}\quad & \text{pu}_{L}^{\uparrow M}\bef\text{sw}_{L,M}=\text{pu}_{L}\quad,\\
{\color{greenunder}\text{inner identity law}:}\quad & \text{pu}_{M}\bef\text{sw}_{L,M}=\text{pu}_{M}^{\uparrow L}\quad.
\end{align*}
Then the identity law holds, $T_{L}^{M}\cong L$ for $M=\text{Id}$,
via monad isomorphisms. 

\subparagraph{Proof}

First consider what happens to $\text{sw}_{L,M}$ when $L$ or $M$
are set to the identity monad ($\text{Id}$). For composed-outside
transformers ($T_{L}^{M}=L\circ M$) the foreign monad is $M$. Setting
$M=\text{Id}$ in the inner identity law, we obtain 
\[
\text{pu}_{\text{Id}}\bef\text{sw}_{L,\text{Id}}=\text{pu}_{\text{Id}}^{\uparrow L}\quad.
\]
Since $\text{pu}_{\text{Id}}=\text{id}$, it follows that $\text{sw}_{L,\text{Id}}=\text{id}$.
In a similar way, for composed-inside transformers ($T_{L}^{M}=M\circ L$)
we need to switch the roles of $M$ and $L$ in the same computation
and substitute $L=\text{id}$ into the outer identity law,
\[
\text{pu}_{\text{Id}}^{\uparrow M}\bef\text{sw}_{\text{Id},M}=\text{pu}_{\text{Id}}\quad.
\]
We obtain $\text{sw}_{\text{Id},M}=\text{id}$.

\begin{comment}
Note that $\text{sw}_{L,\text{Id}}:L^{A}\rightarrow L^{A}$ is a natural
transformation for a monad $L$, so one may heuristically expect $\text{sw}_{L,\text{Id}}$
to be equal to the identity map (the only natural transformation $L^{A}\rightarrow L^{A}$
that exists for all monads $L$). Similarly, one may expect that $\text{sw}_{\text{Id},M}:M^{A}\rightarrow M^{A}=\text{id}$
since it is a natural transformation. But these are only heuristic
expectations, while we have just shown that the properties $\text{sw}_{L,\text{Id}}=\text{id}$
and $\text{sw}_{\text{Id},M}=\text{id}$ follow from the previously
established laws of \lstinline!swap! without any new assumptions.
These properties will be needed in the proofs below. 
\end{comment}
To demonstrate a monadic isomorphism between the monads $T_{L}^{\text{Id}}$
and $L$, we will consider separately the cases of composed-inside
and composed-outside transformers.

For composed-inside transformers $T_{L}^{M}=M\circ L$, we set $M=\text{Id}$
and find that the monad $T_{L}^{\text{Id}}=\text{Id}\circ L=L$ is
the same type constructor as $L$. So, the isomorphism maps between
$T_{L}^{\text{Id}}$ and $L$ are simply the identity maps in both
directions, $\text{id}:T_{L}^{\text{Id},A}\rightarrow L^{A}$ and
$\text{id}:L^{A}\rightarrow T_{L}^{\text{Id},A}$. 

For composed-outside transformers $T_{L}^{M}=L\circ M$, the monad
$T_{L}^{\text{Id}}=L\circ\text{Id}=L$ is again the same type constructor
as $L$. The isomorphisms between $T_{L}^{\text{Id}}$ and $L$ are
again the identity maps in both directions, $\text{id}:T_{L}^{\text{Id},A}\rightarrow L^{A}$
and $\text{id}:L^{A}\rightarrow T_{L}^{\text{Id},A}$. 

We have found the isomorphism maps between $T_{L}^{\text{Id}}$ and
$L$. However, we still need to verify that the monad structure of
$T_{L}^{\text{Id}}$ is the same as that of $L$; otherwise the isomorphism
would not be a \emph{monad} morphism (i.e., an isomorphism that preserves
the structure of the monads). To verify this, it is sufficient to
show that the methods $\text{pu}_{T}$ and $\text{ftn}_{T}$ defined
by Eqs.~(\ref{eq:def-pure-T-via-pure-L-and-pure-M})\textendash (\ref{eq:def-flatten-T-via-sw-and-flatten-L-M})
for the monad $T_{L}^{\text{Id}}$ are \emph{the same functions} as
the given methods $\text{pu}_{L}$ and $\text{ftn}_{L}$ of the monad
$L$. If the monad\textsf{'}s methods are the same functions, i.e.~$\text{pu}_{L}=\text{pu}_{T}$
and $\text{ftn}_{L}=\text{ftn}_{T}$, then the identity map $\text{id}:T^{A}\rightarrow L^{A}$
will satisfy the laws of the monad morphisms:
\[
\text{pu}_{T}\bef\text{id}=\text{pu}_{L}\quad,\quad\quad\text{ftn}_{T}\bef\text{id}=\text{id}^{\uparrow T}\bef\text{id}\bef\text{ftn}_{L}\quad.
\]
In the same way, the laws of the monad morphisms will hold for \textsf{``}$\text{id}$\textsf{''}
in the direction $L\leadsto T$. 

\paragraph{For composed-inside transformers:}

We need to show that $\text{pu}_{M}=\text{pu}_{T}$ and $\text{ftn}_{M}=\text{ftn}_{T}$.
Designate $L$ as the foreign monad and $M$ as the base monad in
Eq.~(\ref{eq:def-pure-T-via-pure-L-and-pure-M}), as appropriate
for the composed-inside transformer $T_{L}^{M}=M\circ L$. Setting
the foreign monad to identity, $L=\text{Id}$, in Eq.~(\ref{eq:def-pure-T-via-pure-L-and-pure-M})
gives
\[
\text{pu}_{T}=\text{pu}_{M}\bef\text{pu}_{\text{Id}}=\text{pu}_{M}.
\]

To show that $\text{ftn}_{M}=\text{ftn}_{T}$, we use Eq.~(\ref{eq:def-flatten-T-via-sw-and-flatten-L-M})
with $L=\text{Id}$:
\begin{align*}
{\color{greenunder}\text{use Eq.~(\ref{eq:def-flatten-T-via-sw-and-flatten-L-M})}:}\quad & \text{ftn}_{T}=\text{sw}_{\text{Id},M}^{\uparrow\text{Id}}\bef\text{ftn}_{\text{Id}}\bef\text{ftn}_{M}^{\uparrow\text{Id}}\\
{\color{greenunder}\text{use }\text{ftn}_{\text{Id}}=\text{id}\text{ and }\text{sw}_{\text{Id},M}=\text{id}:}\quad & =\text{ftn}_{M}\quad.
\end{align*}


\paragraph{For composed-outside transformers:}

We need to show that $\text{pu}_{L}=\text{pu}_{T}$ and $\text{ftn}_{L}=\text{ftn}_{T}$.
Designate $M$ as the foreign monad and $L$ as the base monad in
Eq.~(\ref{eq:def-pure-T-via-pure-L-and-pure-M}), as appropriate
for the composed-outside transformer $T_{L}^{M}=L\circ M$. Setting
the foreign monad to identity, $M=\text{Id}$, in Eq.~(\ref{eq:def-pure-T-via-pure-L-and-pure-M})
gives
\[
\text{pu}_{T}=\text{pu}_{\text{Id}}\bef\text{pu}_{L}=\text{pu}_{L}.
\]

To show that $\text{ftn}_{L}=\text{ftn}_{T}$, use Eq.~(\ref{eq:def-flatten-T-via-sw-and-flatten-L-M})
with $M=\text{Id}$:
\begin{align*}
{\color{greenunder}\text{use Eq.~(\ref{eq:def-flatten-T-via-sw-and-flatten-L-M})}:}\quad & \text{ftn}_{T}=\text{sw}_{L,\text{Id}}^{\uparrow L}\bef\text{ftn}_{L}\bef\text{ftn}_{\text{Id}}^{\uparrow L}\\
{\color{greenunder}\text{use }\text{ftn}_{\text{Id}}=\text{id}\text{ and }\text{sw}_{L,\text{Id}}=\text{id}:}\quad & =\text{ftn}_{L}\quad.
\end{align*}


\subsection{Monad transformer lifting laws. Proofs}

\subsubsection{Statement \label{subsec:Statement-transformer-lifting-laws-from-swap}\ref{subsec:Statement-transformer-lifting-laws-from-swap}}

The monad transformer lifting laws hold if the monad methods of $T$
are defined using Eqs.~(\ref{eq:def-pure-T-via-pure-L-and-pure-M})\textendash (\ref{eq:def-flatten-T-via-sw-and-flatten-L-M}),
and if the \lstinline!swap! function obeys the laws defined in Statement~\ref{sec:Statement-swap-laws-to-monad-transformer-first-law}.

\subparagraph{Proof}

To be specific, let us assume that $L$ is the base monad of the transformer.
For the other choice of the base monad, we only need to interchange
the definitions of \lstinline!flift! and \lstinline!blift!.

The lift functions of a compositional monad transformer are:
\[
\text{flift}=\text{pu}_{L}:M^{A}\rightarrow L^{M^{A}}\quad,\quad\quad\text{blift}=\text{pu}_{M}^{\uparrow L}:L^{A}\rightarrow L^{M^{A}}\quad.
\]
Their laws of monad morphisms (the identity and the composition laws)
are 
\begin{align*}
\text{pu}_{M}\bef\text{flift}=\text{pu}_{T}\quad,\quad & \quad\text{pu}_{L}\bef\text{blift}=\text{pu}_{T}\quad,\\
\text{ftn}_{M}\bef\text{flift}=\text{flift}^{\uparrow M}\bef\text{flift}\bef\text{ftn}_{T}\quad,\quad & \quad\text{ftn}_{L}\bef\text{blift}=\text{blift}^{\uparrow L}\bef\text{blift}\bef\text{ftn}_{T}\quad.
\end{align*}
The identity laws are verified quickly:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{pu}_{T}:}\quad & \text{pu}_{M}\bef\text{flift}=\text{pu}_{M}\bef\text{pu}_{L}=\text{pu}_{T}\quad,\\
{\color{greenunder}\text{expect to equal }\text{pu}_{T}:}\quad & \text{pu}_{L}\bef\text{blift}=\text{pu}_{L}\bef\text{pu}_{M}^{\uparrow L}=\text{pu}_{M}\bef\text{pu}_{L}=\text{pu}_{T}\quad.
\end{align*}
To verify the composition laws, we need to start from their right-hand
sides because the left-hand sides cannot be simplified. We then substitute
the definition of $\text{ftn}_{T}$ in terms of \lstinline!swap!.

The composition law for \lstinline!flift!:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{ftn}_{M}\bef\text{pu}_{L}:}\quad & \text{flift}^{\uparrow M}\bef\text{flift}\bef\text{ftn}_{T}\\
{\color{greenunder}\text{definitions of }\text{flift}\text{ and }\text{ftn}_{T}:}\quad & =\text{pu}_{L}^{\uparrow M}\bef\gunderline{\text{pu}_{L}\bef\text{sw}^{\uparrow L}}\bef\text{ftn}_{L}\bef\text{ftn}_{M}^{\uparrow L}\\
{\color{greenunder}\text{naturality law of }\text{pu}_{L}:}\quad & =\text{pu}_{L}^{\uparrow M}\bef\text{sw}\bef\gunderline{\text{pu}_{L}\bef\text{ftn}_{L}}\bef\text{ftn}_{M}^{\uparrow L}\\
{\color{greenunder}\text{left identity law of }L:}\quad & =\gunderline{\text{pu}_{L}^{\uparrow M}\bef\text{sw}}\bef\text{ftn}_{M}^{\uparrow L}\\
{\color{greenunder}\text{inner identity law of }\text{sw}:}\quad & =\text{pu}_{L}\bef\text{ftn}_{M}^{\uparrow L}=\text{ftn}_{M}\bef\text{pu}_{L}\quad.
\end{align*}

The composition law for \lstinline!blift!:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{ftn}_{L}\bef\text{pu}_{M}^{\uparrow L}:}\quad & \text{blift}^{\uparrow L}\bef\text{blift}\bef\text{ftn}_{T}\\
{\color{greenunder}\text{definitions of }\text{blift}\text{ and }\text{ftn}_{T}:}\quad & =\text{pu}_{M}^{\uparrow L\uparrow L}\bef\gunderline{\text{pu}_{M}^{\uparrow L}\bef\text{sw}^{\uparrow L}}\bef\text{ftn}_{L}\bef\text{ftn}_{M}^{\uparrow L}\\
{\color{greenunder}\text{functor composition in }L:}\quad & =\text{pu}_{M}^{\uparrow L\uparrow L}\bef\gunderline{\left(\text{pu}_{M}\bef\text{sw}\right)}^{\uparrow L}\bef\text{ftn}_{L}\bef\text{ftn}_{M}^{\uparrow L}\\
{\color{greenunder}\text{outer identity law of }\text{sw}:}\quad & =\gunderline{\big(\text{pu}_{M}^{\uparrow L\uparrow L}\bef\text{pu}_{M}^{\uparrow L\uparrow L}\big)}\bef\gunderline{\text{ftn}_{L}}\bef\text{ftn}_{M}^{\uparrow L}\\
{\color{greenunder}\text{naturality law of }\text{ftn}_{L}:}\quad & =\text{ftn}_{L}\bef\big(\text{pu}_{M}^{\uparrow L}\bef\gunderline{\text{pu}_{M}^{\uparrow L}\big)\bef\text{ftn}_{M}^{\uparrow L}}\\
{\color{greenunder}\text{right identity law of }M:}\quad & =\text{ftn}_{L}\bef\text{pu}_{M}^{\uparrow L}\quad.
\end{align*}

So, the lifting laws for $T$ follow from the laws of \lstinline!swap!.

\subsection{Monad transformer runner laws. Proofs}

\subsubsection{Statement \label{subsec:Statement-monad-transformer-runner-laws-from-swap}\ref{subsec:Statement-monad-transformer-runner-laws-from-swap}}

The runners (\lstinline!frun! and \lstinline!brun!) satisfy the
runner laws and the base runner laws, as long as the \lstinline!swap!
function is monadically natural as given by Eqs.~(\ref{eq:monadic-naturality-of-sw-l-m})
or~(\ref{eq:monadic-naturality-sw-n-m}) below. Compositional monad
transformers have general base runners, $\text{brun}\left(\theta\right)$,
that satisfy the laws for any lawful runner $\theta:L\leadsto\text{Id}$.
The functions \lstinline!frun! and \lstinline!brun! also satisfy
the monadic naturality laws.

\subparagraph{Proof}

The laws of runners are not symmetric with respect to the base monad
and the foreign monad: the runners are parametric in the foreign monad
but not in the base monad. In each case, the \lstinline!swap! function
must be monadically natural with respect to the \emph{foreign} monad.
So, the laws need to be written differently, depending on the choice
of the base monad. Let us consider separately the cases where either
$L$ or $M$ is the base monad.

\paragraph{(a) If the base monad is $L$, }

the runners are defined by
\begin{align*}
\text{frun}\,(\phi^{:M\leadsto N}) & :L\circ M\leadsto L\circ N\quad,\quad\quad\text{frun}\,(\phi)=\phi^{\uparrow L}\quad;\\
\text{brun}\,(\theta^{:L\leadsto\text{Id}}) & :L\circ M\leadsto M\quad,\quad\quad\text{brun}\,(\theta)=\theta\quad.
\end{align*}
The laws of runners require that $\text{frun}\,(\phi)$ and $\text{brun}\,(\theta)$
must be monad morphisms, i.e., the identity and composition laws must
hold:
\begin{align*}
 & \text{pu}_{L\circ M}\bef\text{frun}\,(\phi)=\text{pu}_{L\circ N}\quad,\quad\quad\text{ftn}_{L\circ M}\bef\text{frun}\,(\phi)=\left(\text{frun}\,(\phi)\right)^{\uparrow M\uparrow L}\bef\text{frun}\,(\phi)\bef\text{ftn}_{L\circ N}\quad,\\
 & \text{pu}_{L\circ M}\bef\text{brun}\,(\theta)=\text{pu}_{M}\quad,\quad\quad\text{ftn}_{L\circ M}\bef\text{brun}\,(\theta)=\left(\text{brun}\,(\theta)\right)^{\uparrow M\uparrow L}\bef\text{brun}\,(\theta)\bef\text{ftn}_{M}\quad.
\end{align*}
To derive these laws, we may use the identity and composition laws
of monad morphisms for $\phi$ and $\theta$. We also use Eqs.~(\ref{eq:def-pure-T-via-pure-L-and-pure-M})\textendash (\ref{eq:def-flatten-T-via-sw-and-flatten-L-M})
as definitions of the monad $T$. Additionally, we assume the \textbf{monadic
naturality}\index{monadic naturality law!of swap@of \texttt{swap}}
of \lstinline!swap! with respect to $\phi$ and $\theta$,
\begin{equation}
\text{sw}_{L,M}\bef\phi^{\uparrow L}=\phi\bef\text{sw}_{L,N}\quad,\quad\quad\text{sw}_{L,M}\bef\theta=\theta^{\uparrow M}\quad.\label{eq:monadic-naturality-of-sw-l-m}
\end{equation}
\[
\xymatrix{\xyScaleY{1.5pc}\xyScaleX{3pc}M^{L^{A}}\ar[r]\sp(0.5){\text{sw}_{L,M}}\ar[d]\sb(0.4){\phi} & L^{M^{A}}\ar[d]\sp(0.4){\phi^{\uparrow L}} & M^{L^{A}}\ar[r]\sp(0.5){\text{sw}_{L,M}}\ar[rd]\sb(0.45){\theta^{\uparrow M}} & L^{M^{A}}\ar[d]\sp(0.4){\theta}\\
N^{L^{A}}\ar[r]\sb(0.5){\text{sw}_{L,N}} & L^{N^{A}} &  & M^{A}
}
\]

The first law to be shown is the identity law of $\text{frun}\,(\phi)$:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{pu}_{L\circ N}:}\quad & \text{pu}_{L\circ M}\bef\text{frun}\,(\phi)\\
{\color{greenunder}\text{definitions of }\text{frun}\text{ and }\text{pu}_{L\circ M}:}\quad & =\text{pu}_{M}\bef\gunderline{\text{pu}_{L}\bef\phi^{\uparrow L}}\\
{\color{greenunder}\text{naturality law of }\text{pu}_{L}:}\quad & =\gunderline{\text{pu}_{M}\bef\phi}\bef\text{pu}_{L}\\
{\color{greenunder}\text{identity law of }\phi:}\quad & =\text{pu}_{N}\bef\text{pu}_{L}\\
{\color{greenunder}\text{definition of }\text{pu}_{L\circ N}:}\quad & =\text{pu}_{L\circ N}\quad.
\end{align*}

The next law to be verified is the composition law of $\text{frun}\,(\phi)$:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{ftn}_{T}\bef\phi^{\uparrow L}:}\quad & (\text{frun}\,(\phi))^{\uparrow M\uparrow L}\bef\text{frun}\,(\phi)\bef\text{ftn}_{L\circ N}\\
{\color{greenunder}\text{definitions of }\text{frun}\text{ and }\text{ftn}_{L\circ N}:}\quad & =\phi^{\uparrow L\uparrow M\uparrow L}\bef\gunderline{\phi^{\uparrow L}\bef\text{sw}_{L,N}^{\uparrow L}}\bef\text{ftn}_{L}\bef\text{ftn}_{N}^{\uparrow L}\\
{\color{greenunder}\text{monadic naturality law of }\text{sw}_{L,M}:}\quad & =\gunderline{\phi^{\uparrow L\uparrow M\uparrow L}\bef\text{sw}_{L,M}^{\uparrow L}}\bef\phi^{\uparrow L\uparrow L}\bef\text{ftn}_{L}\bef\text{ftn}_{N}^{\uparrow L}\\
{\color{greenunder}\text{naturality law of }\text{sw}_{L,M}:}\quad & =\text{sw}_{L,M}^{\uparrow L}\bef\gunderline{\phi^{\uparrow M\uparrow L\uparrow L}\bef\phi^{\uparrow L\uparrow L}\bef\text{ftn}_{L}}\bef\text{ftn}_{N}^{\uparrow L}\\
{\color{greenunder}\text{naturality law of }\text{ftn}_{L}:}\quad & =\text{sw}_{L,M}^{\uparrow L}\bef\text{ftn}_{L}\bef\gunderline{(\phi^{\uparrow M}\bef\phi\bef\text{ftn}_{N})}^{\uparrow L}\\
{\color{greenunder}\text{composition law of }\phi:}\quad & =\gunderline{\text{sw}_{L,M}^{\uparrow L}\bef\text{ftn}_{L}\bef\text{ftn}_{M}^{\uparrow L}}\bef\phi^{\uparrow L}\\
{\color{greenunder}\text{definition of }\text{ftn}_{T}:}\quad & =\gunderline{\text{ftn}_{T}}\bef\phi^{\uparrow L}\quad.
\end{align*}

The next law is the identity law for \lstinline!brun!:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{pu}_{M}:}\quad & \text{pu}_{L\circ M}\bef\text{brun}\,\theta\\
{\color{greenunder}\text{definitions of }\text{brun}\text{ and }\text{pu}_{L\circ M}:}\quad & =\text{pu}_{M}\bef\gunderline{\text{pu}_{L}\bef\theta}\\
{\color{greenunder}\text{identity law of }\theta:}\quad & =\text{pu}_{M}\quad.
\end{align*}

The last law is the composition law for \lstinline!brun!. Begin with
its right-hand side since it is longer:
\begin{align*}
 & \left(\text{brun}\,(\theta)\right)^{\uparrow M\uparrow L}\bef\text{brun}\,(\theta)\bef\text{ftn}_{M}\\
{\color{greenunder}\text{definition of }\text{brun}:}\quad & =\theta^{\uparrow M\uparrow L}\bef\theta\bef\text{ftn}_{M}\quad.
\end{align*}
We cannot simplify this expression any more, and yet it is still different
from the left-hand side. So let us transform the left-hand side, hoping
to obtain the same expression. In particular, we need to move $\text{ftn}_{M}$
to the right and $\theta$ to the left: 
\begin{align*}
 & \text{ftn}_{L\circ M}\bef\text{brun}\,(\theta)\\
{\color{greenunder}\text{definitions of }\text{ftn}_{L\circ M}\text{ and }\text{brun}:}\quad & =\text{sw}_{L,M}^{\uparrow L}\bef\text{ftn}_{L}\bef\gunderline{\text{ftn}_{M}^{\uparrow L}\bef\theta}\\
{\color{greenunder}\text{naturality law of }\theta:}\quad & =\text{sw}_{L,M}^{\uparrow L}\bef\gunderline{\text{ftn}_{L}\bef\theta}\bef\text{ftn}_{M}\\
{\color{greenunder}\text{composition law of }\theta:}\quad & =\gunderline{\text{sw}_{L,M}^{\uparrow L}\bef\theta^{\uparrow L}}\bef\theta\bef\text{ftn}_{M}\\
{\color{greenunder}\text{functor composition}:}\quad & =\gunderline{\left(\text{sw}_{L,M}\bef\theta\right)^{\uparrow L}}\bef\theta\bef\text{ftn}_{M}\\
{\color{greenunder}\text{monadic naturality law of }\text{sw}_{L,M}:}\quad & =\gunderline{\theta^{\uparrow M\uparrow L}}\bef\theta\bef\text{ftn}_{M}\quad.
\end{align*}
We have transformed both sides of the law into the same expression.

The functor laws for \lstinline!frun! are
\[
\text{frun}\left(\text{id}\right)=\text{id}\quad,\quad\quad\text{frun}\left(\phi\right)\bef\text{frun}\left(\chi\right)=\text{frun}\left(\phi\bef\chi\right)\quad.
\]
Since $\text{frun}\left(\phi\right)=\phi^{\uparrow L}$ in our case,
these laws hold because they are the same as the functor laws of $L$.

To verify the non-degeneracy law for \lstinline!brun!:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{id}:}\quad & \text{flift}\bef\text{brun}\left(\theta\right)\\
{\color{greenunder}\text{definitions of }\text{flift}\text{ and }\text{brun}:}\quad & =\text{pu}_{L}\bef\theta\\
{\color{greenunder}\text{identity law of }\theta:}\quad & =\text{id}\quad.
\end{align*}

Finally, we need to check the monadic naturality laws of \lstinline!flift!
and \lstinline!brun!:
\[
\phi^{:M\leadsto N}\bef\text{flift}_{L}^{N}=\text{flift}_{L}^{M}\bef(\phi^{:M\leadsto N})^{\uparrow L}\quad,\quad\quad(\phi^{:M\leadsto N})^{\uparrow L}\bef\text{brun}_{L}^{N}(\theta_{L})=\text{brun}_{L}^{M}(\theta_{L})\bef\phi^{:M\leadsto N}\quad.
\]
To verify these laws, use the naturality laws of $\text{pu}_{L}$
and $\theta_{L}$:
\begin{align*}
 & \phi\bef\text{flift}=\gunderline{\phi\bef\text{pu}_{L}}=\text{pu}_{L}\bef\phi^{\uparrow L}=\text{flift}\bef\phi^{\uparrow L}\quad,\\
 & \phi^{\uparrow L}\bef\text{brun}\,(\theta_{L})=\gunderline{\phi^{\uparrow L}\bef\theta_{L}}=\theta_{L}\bef\phi=\text{brun}\,(\theta_{L})\bef\phi\quad.
\end{align*}


\paragraph{(b) If the base monad is $M$, }

the runners are defined by
\begin{align*}
\text{frun}\,(\phi^{:L\leadsto N}) & :L\circ M\leadsto N\circ M\quad,\quad\quad\text{frun}\,(\phi)=\phi\quad;\\
\text{brun}\,(\theta^{:M\leadsto\text{Id}}) & :L\circ M\leadsto L\quad,\quad\quad\text{brun}\,(\theta)=\theta^{\uparrow L}\quad.
\end{align*}
The laws of runners require that $\text{frun}\,(\phi)$ and $\text{brun}\,(\theta)$
must be monad morphisms, i.e., the identity and composition laws must
hold:
\begin{align*}
 & \text{pu}_{L\circ M}\bef\text{frun}\,(\phi)=\text{pu}_{N\circ M}\quad,\quad\quad\text{ftn}_{L\circ M}\bef\text{frun}\,(\phi)=\left(\text{frun}\,(\phi)\right)^{\uparrow M\uparrow L}\bef\text{frun}\,(\phi)\bef\text{ftn}_{N\circ M}\quad,\\
 & \text{pu}_{L\circ M}\bef\text{brun}\,(\theta)=\text{pu}_{L}\quad,\quad\quad\text{ftn}_{L\circ M}\bef\text{brun}\,(\theta)=\left(\text{brun}\,(\theta)\right)^{\uparrow M\uparrow L}\bef\text{brun}\,(\theta)\bef\text{ftn}_{L}\quad.
\end{align*}
The monadic naturality laws of \lstinline!swap! with respect to $\phi$
and $\chi$ are
\begin{equation}
\text{sw}_{L,M}\bef\phi=\phi^{\uparrow M}\bef\text{sw}_{N,M}\quad,\quad\quad\text{sw}_{L,M}\bef\theta^{\uparrow L}=\theta\quad.\label{eq:monadic-naturality-sw-n-m}
\end{equation}
\[
\xymatrix{\xyScaleY{1.5pc}\xyScaleX{3pc}M^{L^{A}}\ar[r]\sp(0.5){\text{sw}_{L,M}}\ar[d]\sb(0.4){\phi^{\uparrow M}} & L^{M^{A}}\ar[d]\sp(0.4){\phi} & M^{L^{A}}\ar[r]\sp(0.5){\text{sw}_{L,M}}\ar[rd]\sb(0.45){\theta} & L^{M^{A}}\ar[d]\sp(0.4){\theta^{\uparrow L}}\\
M^{N^{A}}\ar[r]\sb(0.5){\text{sw}_{N,M}} & N^{M^{A}} &  & L^{A}
}
\]

The first law to be proved is the identity law of $\text{frun}\,(\phi)$
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{pu}_{N\circ M}:}\quad & \text{pu}_{L\circ M}\bef\text{frun}\,(\phi)\\
{\color{greenunder}\text{definitions of }\text{frun}\text{ and }\text{pu}_{L\circ M}:}\quad & =\text{pu}_{M}\bef\gunderline{\text{pu}_{L}\bef\phi}\\
{\color{greenunder}\text{identity law of }\phi:}\quad & =\text{pu}_{M}\bef\text{pu}_{N}\\
{\color{greenunder}\text{definition of }\text{pu}_{N\circ M}:}\quad & =\text{pu}_{N\circ M}\quad.
\end{align*}

The next law is the composition law of $\text{frun}\,(\phi)$:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{ftn}_{T}\bef\phi:}\quad & \left(\text{frun}\,(\phi)\right)^{\uparrow M\uparrow L}\bef\text{frun}\,(\phi)\bef\text{ftn}_{N\circ M}\\
{\color{greenunder}\text{definitions of }\text{frun}\text{ and }\text{ftn}_{N\circ M}:}\quad & =\phi^{\uparrow M\uparrow L}\bef\gunderline{\phi\bef\text{sw}_{N,M}^{\uparrow N}}\bef\text{ftn}_{N}\bef\text{ftn}_{M}^{\uparrow N}\\
{\color{greenunder}\text{naturality law of }\phi:}\quad & =\gunderline{\phi^{\uparrow M\uparrow L}\bef\text{sw}_{N,M}^{\uparrow L}}\bef\phi\bef\text{ftn}_{N}\bef\text{ftn}_{M}^{\uparrow N}\\
{\color{greenunder}\text{monadic naturality of }\text{sw}_{N,M}\text{ raised to }L:}\quad & =\text{sw}_{L,M}^{\uparrow L}\bef\gunderline{\phi^{\uparrow L}\bef\phi\bef\text{ftn}_{N}}\bef\text{ftn}_{M}^{\uparrow N}\\
{\color{greenunder}\text{composition law of }\phi:}\quad & =\text{sw}_{L,M}^{\uparrow L}\bef\text{ftn}_{L}\bef\gunderline{\phi\bef\text{ftn}_{M}^{\uparrow N}}\\
{\color{greenunder}\text{naturality law of }\phi:}\quad & =\gunderline{\text{sw}_{L,M}^{\uparrow L}\bef\text{ftn}_{L}\bef\text{ftn}_{M}^{\uparrow L}}\bef\phi\\
{\color{greenunder}\text{definition of }\text{ftn}_{T}:}\quad & =\gunderline{\text{ftn}_{T}}\bef\phi\quad.
\end{align*}

The next law is the identity law of $\text{brun}\left(\theta\right)$:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{pu}_{L}:}\quad & \text{pu}_{L\circ M}\bef\text{brun}\,(\theta)\\
{\color{greenunder}\text{definitions of }\text{brun}\text{ and }\text{pu}_{L\circ M}:}\quad & =\text{pu}_{M}\bef\gunderline{\text{pu}_{L}\bef\theta^{\uparrow L}}=\gunderline{\text{pu}_{M}\bef\theta}\bef\text{pu}_{L}\\
{\color{greenunder}\text{identity law of }\theta:}\quad & =\text{pu}_{L}\quad.
\end{align*}

The last law is the composition law of $\text{brun}\left(\theta\right)$.
Begin with its right-hand side:
\begin{align*}
 & \left(\text{brun}\,(\theta)\right)^{\uparrow M\uparrow L}\bef\text{brun}\,(\theta)\bef\text{ftn}_{L}\\
{\color{greenunder}\text{definition of }\text{brun}:}\quad & =\theta^{\uparrow L\uparrow M\uparrow L}\bef\theta^{\uparrow L}\bef\text{ftn}_{L}\\
{\color{greenunder}\text{functor composition}:}\quad & =(\theta^{\uparrow L\uparrow M}\bef\theta)^{\uparrow L}\bef\text{ftn}_{L}\\
{\color{greenunder}\text{naturality law of }\theta:}\quad & =(\theta\bef\theta^{\uparrow L})^{\uparrow L}\bef\text{ftn}_{L}\quad.
\end{align*}
We now transform the left-hand side, aiming to obtain the same expression.
We need to move $\text{ftn}_{L}$ to the right and $\theta$ to the
left: 
\begin{align*}
{\color{greenunder}\text{expect to equal }\theta^{\uparrow L}\bef\theta^{\uparrow L\uparrow L}\bef\text{ftn}_{L}:}\quad & \text{ftn}_{L\circ M}\bef\text{brun}\,(\theta)\\
{\color{greenunder}\text{definitions of }\text{ftn}_{L\circ M}\text{ and }\text{brun}:}\quad & =\text{sw}_{L,M}^{\uparrow L}\bef\text{ftn}_{L}\bef\gunderline{\text{ftn}_{M}^{\uparrow L}\bef\theta^{\uparrow L}}\\
{\color{greenunder}\text{composition law of }\theta:}\quad & =\text{sw}_{L,M}^{\uparrow L}\bef\gunderline{\text{ftn}_{L}\bef\left(\theta\bef\theta\right)^{\uparrow L}}=\gunderline{\text{sw}_{L,M}^{\uparrow L}\bef\left(\theta\bef\theta\right)^{\uparrow L\uparrow L}}\bef\text{ftn}_{L}\\
{\color{greenunder}\text{functor composition}:}\quad & =\gunderline{(\text{sw}_{L,M}\bef\theta^{\uparrow L})}^{\uparrow L}\bef\theta^{\uparrow L\uparrow L}\bef\text{ftn}_{L}\\
{\color{greenunder}\text{monadic naturality law of }\text{sw}_{L,M}:}\quad & =\gunderline{\theta^{\uparrow L}}\bef\theta^{\uparrow L\uparrow L}\bef\text{ftn}_{L}\quad.
\end{align*}

The functor laws of \lstinline!frun! are
\[
\text{frun}\left(\text{id}\right)=\text{id}\quad,\quad\quad\text{frun}\left(\phi\right)\bef\text{frun}\left(\chi\right)=\text{frun}\left(\phi\bef\chi\right)\quad.
\]
Since $\text{frun}\left(\phi\right)=\phi$ in our case, these laws
are satisfied.

To verify the non-degeneracy law of \lstinline!brun!:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{id}:}\quad & \text{flift}\bef\text{brun}\left(\theta\right)\\
{\color{greenunder}\text{definitions of }\text{flift}\text{ and }\text{brun}:}\quad & =\text{pu}_{M}^{\uparrow L}\bef\theta^{\uparrow L}=\text{id}^{\uparrow L}=\text{id}\quad.
\end{align*}

Finally, we need to check the monadic naturality laws of \lstinline!flift!
and \lstinline!brun!:
\[
\phi^{:L\leadsto K}\bef\text{flift}_{M}^{K}=\text{flift}_{M}^{L}\bef\phi^{:L\leadsto K}\quad,\quad\quad\phi^{:L\leadsto K}\bef\text{brun}_{M}^{K}(\theta_{M})=\text{brun}_{M}^{L}(\theta_{M})\bef\phi^{:L\leadsto K}\quad.
\]
To verify these laws, use the naturality law of $\phi^{:L\leadsto K}$:
\begin{align*}
 & \phi\bef\text{flift}_{M}^{K}=\gunderline{\phi\bef\text{pu}_{M}^{\uparrow K}}=\text{pu}_{M}^{\uparrow L}\bef\phi=\text{flift}_{N}^{L}\bef\phi\quad,\\
 & \phi\bef\text{brun}_{M}^{K}(\theta_{M})=\gunderline{\phi\bef\theta_{M}^{\uparrow K}}=\theta_{M}^{\uparrow L}\bef\phi=\text{brun}_{M}^{L}(\theta_{M})\bef\phi\quad.
\end{align*}


\subsection{Summary of results}

The following two statements summarize the derivations in Section~\ref{sec:Monad-transformers-that-use-composition}.

\subsubsection{Statement \label{subsec:Statement-outside-transformer-swap-laws}\ref{subsec:Statement-outside-transformer-swap-laws}
(composed-outside)}

For a base monad $L$ and a foreign monad $M$, the functor composition
$L\circ M$ is a lawful monad transformer if a \lstinline!swap! function
$\text{sw}_{L,M}:M\circ L\leadsto L\circ M$ exists, satisfying the
conditions of Statement~\ref{sec:Statement-swap-laws-to-monad-transformer-first-law}
and the monadic naturality laws
\[
\text{sw}_{L,M}\bef\phi^{\uparrow L}=\phi\bef\text{sw}_{L,N}\quad,\quad\quad\text{sw}_{L,M}\bef\theta=\theta^{\uparrow M}\quad,
\]
with arbitrary monad morphisms $\phi:M\leadsto N$ and $\theta:L\leadsto\text{Id}$.
An additional law, $\text{sw}_{L,\text{Id}}=\text{id}$, follows from
the conditions of Statement~\ref{sec:Statement-swap-laws-to-monad-transformer-first-law}.

\subsubsection{Statement \label{subsec:Statement-inside-transformer-swap-laws}\ref{subsec:Statement-inside-transformer-swap-laws}
(composed-inside)}

For a base monad $M$ and a foreign monad $L$, the functor composition
$L\circ M$ is a lawful monad transformer if a \lstinline!swap! function
$\text{sw}_{L,M}:M\circ L\leadsto L\circ M$ exists, satisfying the
conditions of Statement~\ref{sec:Statement-swap-laws-to-monad-transformer-first-law}
and the monadic naturality laws
\[
\text{sw}_{L,M}\bef\phi=\phi^{\uparrow M}\bef\text{sw}_{N,M}\quad,\quad\quad\text{sw}_{L,M}\bef\theta^{\uparrow L}=\theta\quad,
\]
with respect to arbitrary monad morphisms $\phi:L\leadsto N$ and
$\theta:M\leadsto\text{Id}$. An additional law, $\text{sw}_{\text{Id},M}=\text{id}$,
follows from the conditions of Statement~\ref{sec:Statement-swap-laws-to-monad-transformer-first-law}.

In many cases, Statements~\ref{subsec:Statement-outside-transformer-swap-laws}\textendash \ref{subsec:Statement-inside-transformer-swap-laws}
make monad transformer proofs quicker because the 6 laws of \lstinline!swap!
replace the 18 monad transformer laws and also use simpler types.

\section{Composed-inside transformers for linear monads\label{sec:transformers-linear-monads}}

In the previous section, we derived a number of properties common
to all compositional transformers. We will now use those properties
to prove the laws of composed-outside transformers. All those transformers
have a \textsf{``}linear\textsf{''} monad as their base monad.

A monad $M$ is\textbf{ linear}\index{monads!linear} if its type
is of the form $M^{A}\triangleq P+Q\times A$, where $P$ and $Q$
are fixed types and $Q$ is a monoid. (The name \textsf{``}linear\textsf{''} is motivated
by considering the polynomial $P+Q\times A$, which is linear in the
parameter $A$.) Well-known examples of linear monads are \lstinline!Option!,
\lstinline!Either!, and \lstinline!Writer!. The effect of the monad
$M^{A}\triangleq P+Q\times A$ combines the effects of \lstinline!Either!
and \lstinline!Writer! monads: a computation that can either succeed
and append a log message (of type $Q$), or fail (with an error of
type $P$).

A different (but also linear) monad is obtained from the composition
of \lstinline!Writer! and \lstinline!Either!. The type constructor
of this monad is $Q\times\left(P+A\right)$. This monad\textsf{'}s effect is
to append to a monoid $Q$ and, at the same time, to compute a value
of type $A$ or to fail with an error of type $P$.

A composition of two linear monads $M_{1}^{A}\triangleq P_{1}+Q_{1}\times A$
and $M_{2}^{A}\triangleq P_{2}+Q_{2}\times A$ is again linear:
\begin{align*}
 & P_{1}+Q_{1}\times\left(P_{2}+Q_{2}\times A\right)\\
{\color{greenunder}\text{expand brackets}:}\quad & \cong\gunderline{P_{1}+Q_{1}\times P_{2}}+\gunderline{Q_{1}\times Q_{2}}\times A\\
{\color{greenunder}\text{define new }P\text{ and }Q:}\quad & \cong P+Q\times A\quad.
\end{align*}
By assumption, $Q_{1}$ and $Q_{2}$ are monoids, so $Q\triangleq Q_{1}\times Q_{2}$
is also a monoid.

For a linear monad $M$ and any foreign monad $L$, the functor composition
$L\circ M$ is a monad. For example, the type constructor for the
\lstinline!OptionT! monad transformer can be written as
\begin{lstlisting}
type OptionT[L[_], A] = L[Option[A]]
\end{lstlisting}
The \lstinline!Option! type constructor must be composed \emph{inside}
the foreign monad \lstinline!L!. This is the case for all linear
monads. Also, linear monads are the only known examples of monads
whose transformers are defined by composing inside the foreign monad.

\subsection{Definitions of \texttt{swap} and \texttt{flatten}}

To show that $T_{M}^{L,A}=L^{M^{A}}$ is a lawful monad transformer
for the base monad $M^{A}\triangleq P+Q\times A$, we will implement
a suitable \lstinline!swap! function having the type signature
\[
\text{sw}_{L,M}:M^{L^{A}}\rightarrow L^{M^{A}}\quad,
\]
for the base monad $M$ and an arbitrary foreign monad $L$. We will
then prove that \lstinline!swap! satisfies all the laws stated in
Statement~\ref{subsec:Statement-inside-transformer-swap-laws}. This
will guarantee that $T_{M}^{L,A}$ is a lawful monad transformer.

Expanding the definition of the type constructor $M^{\bullet}$, we
can write the type signature of \lstinline!swap! as 
\[
\text{sw}_{L,M}:P+Q\times L^{A}\rightarrow L^{P+Q\times A}\quad.
\]
We can map $P$ to $L^{P}$ by applying $\text{pu}_{L}$. We can also
map $Q\times L^{A}\rightarrow L^{Q\times A}$ since $L$ is a functor:
\[
q\times l\rightarrow l\triangleright\left(a\rightarrow q\times a\right)^{\uparrow L}\quad.
\]
 It remains to combine these two functions. In the matrix notation,
we write:
\begin{equation}
\text{sw}_{L,M}=\,\begin{array}{|c||c|}
 & L^{P+Q\times A}\\
\hline P & (x^{:P}\rightarrow x+\bbnum 0^{:Q\times A})\bef\text{pu}_{L}\\
Q\times L^{A} & q\times l\rightarrow l\triangleright(a^{:A}\rightarrow\bbnum 0^{:P}+q\times a)^{\uparrow L}
\end{array}\quad.\label{eq:single-valued-monad-def-of-swap}
\end{equation}
\begin{lstlisting}
type M[A, P, Q] = Either[P, (Q, A)]
def swap[L[_]: Monad, A, P, Q]: M[L[A]] => L[M[A]] = {
  case Left(p) => Monad[L].pure(Left(p))
  case Right((q, la)) => la.map(a => Right((q, a)))
}
\end{lstlisting}

Given this \lstinline!swap! function, we define the \lstinline!pure!
and \lstinline!flatten! methods for the transformed monad $T$ (short
notation $\text{pu}_{T}$ and $\text{ftn}_{T}$) by the standard formulas
\[
\text{pu}_{T}=\text{pu}_{M}\bef\text{pu}_{L}\quad,\quad\quad\text{ftn}_{T}=\text{sw}^{\uparrow L}\bef\text{ftn}_{L}\bef\text{ftn}_{M}^{\uparrow L}\quad.
\]
\begin{lstlisting}
def pure[L[_]: Monad, A, P, Q: Monoid](x: A): L[M[A]] =
  Monad[L].pure(Right((Monoid[Q].empty, x)))
def flatten[L[_]: Monad, A, P, Q: Monoid](tt: L[M[L[M[A]]]]): L[M[A]] =
  tt.map(swap).flatten.map(_.flatten) // Assuming suitable implicits in scope.
\end{lstlisting}


\subsection{The laws of \texttt{swap}. Proofs}

To verify that the laws of \lstinline!swap! hold, we will need to
use the code for the methods $\text{fmap}_{M}$, $\text{ftn}_{M}$,
and $\text{pu}_{M}$ of the monad $M$:
\begin{align*}
f^{\uparrow M} & =\,\begin{array}{|c||cc|}
 & P & Q\times B\\
\hline P & \text{id} & \bbnum 0\\
Q\times A & \bbnum 0\enskip & q\times a\rightarrow q\times f(a)
\end{array}\quad,\\
\text{pu}_{M}(a^{:A}) & =0^{:P}+q_{0}\times a\quad,\quad\text{or equivalently:}\quad\quad\text{pu}_{M}=\,\begin{array}{|c||cc|}
 & P & Q\times A\\
\hline A & \bbnum 0\enskip & a\rightarrow q_{0}\times a
\end{array}\quad,\\
\text{ftn}_{M}^{:M^{M^{A}}\rightarrow M^{A}} & =\,\begin{array}{|c||cc|}
 & P & Q\times A\\
\hline P & \text{id} & \bbnum 0\\
Q\times P & q\times p\rightarrow p & \bbnum 0\\
Q\times Q\times A & \bbnum 0 & q_{1}\times q_{2}\times a\rightarrow\left(q_{1}\oplus q_{2}\right)\times a
\end{array}\quad.
\end{align*}

We do not have to verify naturality since \lstinline!swap! is defined
as a fully parametric function.

\paragraph{The inner identity law}

We need to show that $\text{pu}_{L}^{\uparrow M}\bef\text{sw}=\text{pu}_{L}$:
\begin{align*}
 & \text{pu}_{L}^{\uparrow M}\bef\text{sw}=\,\left\Vert \begin{array}{cc}
\text{id} & \bbnum 0\\
\bbnum 0 & q\times a\rightarrow q\times\text{pu}_{L}(a)
\end{array}\right|\,\bef\,\left\Vert \begin{array}{c}
(x^{:P}\rightarrow x+\bbnum 0^{:Q\times A})\bef\text{pu}_{L}\\
q\times l\rightarrow l\triangleright(a^{:A}\rightarrow\bbnum 0^{:P}+q\times a)^{\uparrow L}
\end{array}\right|\\
{\color{greenunder}\text{composition}:}\quad & =\,\,\left\Vert \begin{array}{c}
(x^{:P}\rightarrow x+\bbnum 0^{:Q\times A})\bef\text{pu}_{L}\\
q\times a\rightarrow a\triangleright\gunderline{\text{pu}_{L}\bef(a^{:A}\rightarrow\bbnum 0^{:P}+q\times a)^{\uparrow L}}
\end{array}\right|\\
{\color{greenunder}\text{pu}_{L}\text{\textsf{'}s naturality}:}\quad & =\,\left\Vert \begin{array}{c}
(x^{:P}\rightarrow x+\bbnum 0^{:Q\times A})\bef\text{pu}_{L}\\
(q\times a\rightarrow\bbnum 0^{:P}+q\times a)\bef\text{pu}_{L}
\end{array}\right|\,=\,\begin{array}{|c||c|}
P & x^{:P}\rightarrow x+\bbnum 0^{:Q\times A}\\
Q\times A & q\times a\rightarrow\bbnum 0^{:P}+q\times a
\end{array}\,\bef\text{pu}_{L}\\
{\color{greenunder}\text{matrix notation}:}\quad & =\text{id}\bef\text{pu}_{L}=\text{pu}_{L}\quad.
\end{align*}


\paragraph{The outer identity law}

We need to show that $\text{pu}_{M}\bef\text{sw}=\text{pu}_{M}^{\uparrow L}$:
\begin{align*}
 & \text{pu}_{M}\bef\text{sw}=\,\left\Vert \begin{array}{cc}
\bbnum 0 & l^{:L^{A}}\rightarrow q_{0}\times l\end{array}\right|\,\bef\,\left\Vert \begin{array}{c}
(x^{:P}\rightarrow x+\bbnum 0^{:Q\times A})\bef\text{pu}_{L}\\
q\times l\rightarrow l\triangleright(x^{:A}\rightarrow\bbnum 0^{:P}+q\times x)^{\uparrow L}
\end{array}\right|\\
{\color{greenunder}\text{composition}:}\quad & =l^{:L^{A}}\rightarrow l\triangleright(\gunderline{x^{:A}\rightarrow\bbnum 0^{:P}+q_{0}\times x})^{\uparrow L}\\
{\color{greenunder}\text{definition of }\text{pu}_{M}:}\quad & =l\rightarrow l\triangleright\text{pu}_{M}^{\uparrow L}=\text{pu}_{M}^{\uparrow L}\quad.
\end{align*}


\paragraph{The inner interchange law}

We need to show that $\text{ftn}_{L}^{\uparrow M}\bef\text{sw}=\text{sw}\bef\text{sw}^{\uparrow L}\bef\text{ftn}_{L}$:
\begin{align}
\text{ftn}_{L}^{\uparrow M}\bef\text{sw}= & \,\left\Vert \begin{array}{cc}
\text{id} & \bbnum 0\\
\bbnum 0 & q\times l\rightarrow q\times(l\triangleright\text{ftn}_{L})
\end{array}\right|\,\bef\,\left\Vert \begin{array}{c}
(x^{:P}\rightarrow x+\bbnum 0^{:Q\times A})\bef\text{pu}_{L}\\
q\times l\rightarrow l\triangleright(a\rightarrow\bbnum 0^{:P}+q\times a)^{\uparrow L}
\end{array}\right|\nonumber \\
 & =\,\left\Vert \begin{array}{c}
(x^{:P}\rightarrow x+\bbnum 0^{:Q\times A})\bef\text{pu}_{L}\\
q\times l\rightarrow l\triangleright\text{ftn}_{L}\bef(a\rightarrow\bbnum 0^{:P}+q\times a)^{\uparrow L}
\end{array}\right|\quad,\label{eq:l-interchange-derivation1}\\
\text{sw}\bef\text{sw}^{\uparrow L}\bef\text{ftn}_{L}= & \,\left\Vert \begin{array}{c}
(x^{:P}\rightarrow x+\bbnum 0^{:Q\times A})\bef\text{pu}_{L}\\
q\times l\rightarrow l\triangleright(a\rightarrow\bbnum 0^{:P}+q\times a)^{\uparrow L}
\end{array}\right|\,\bef\text{sw}^{\uparrow L}\bef\text{ftn}_{L}\nonumber \\
 & =\,\left\Vert \begin{array}{c}
(x^{:P}\rightarrow x+\bbnum 0^{:Q\times A})\bef\text{pu}_{L}\bef\text{sw}^{\uparrow L}\bef\text{ftn}_{L}\\
\big(q\times l\rightarrow l\triangleright(a\rightarrow\bbnum 0^{:P}+q\times a)^{\uparrow L}\big)\bef\text{sw}^{\uparrow L}\bef\text{ftn}_{L}
\end{array}\right|\quad.\nonumber 
\end{align}
Let us simplify each expression in the last column separately and
then compare with the column in Eq.~(\ref{eq:l-interchange-derivation1}).
Simplify the upper expression:
\begin{align*}
 & (x^{:P}\rightarrow x+\bbnum 0^{:Q\times A})\bef\gunderline{\text{pu}_{L}\bef\text{sw}^{\uparrow L}}\bef\text{ftn}_{L}\\
{\color{greenunder}\text{pu}_{L}\text{\textsf{'}s naturality}:}\quad & =(x^{:P}\rightarrow x+\bbnum 0^{:Q\times A})\bef\text{sw}\bef\gunderline{\text{pu}_{L}\bef\text{ftn}_{L}}\\
{\color{greenunder}\text{identity law of }L:}\quad & =(x^{:P}\rightarrow x+\bbnum 0^{:Q\times A})\bef\text{sw}=x\rightarrow\gunderline{(x^{:P}+\bbnum 0^{:Q\times A})\triangleright\text{sw}}\\
{\color{greenunder}\text{definition of }\text{sw}:}\quad & =x\rightarrow(x+\bbnum 0)\triangleright\,\left\Vert \begin{array}{c}
(x^{:P}\rightarrow x+\bbnum 0^{:Q\times A})\bef\text{pu}_{L}\\
q\times l\rightarrow l\triangleright(a\rightarrow\bbnum 0^{:P}+q\times a)^{\uparrow L}
\end{array}\right|\,=(x^{:P}\rightarrow x+\bbnum 0^{:Q\times A})\bef\text{pu}_{L}\quad.
\end{align*}
This equals the upper expression in Eq.~(\ref{eq:l-interchange-derivation1}).
Simplify the lower expression:
\begin{align}
 & \big(q\times l\rightarrow l\triangleright(a\rightarrow\bbnum 0^{:P}+q\times a)^{\uparrow L}\big)\bef\text{sw}^{\uparrow L}\bef\text{ftn}_{L}\nonumber \\
{\color{greenunder}\triangleright\text{-notation}:}\quad & =q\times l\rightarrow l\triangleright(a\rightarrow\bbnum 0^{:P}+q\times a)^{\uparrow L}\bef\text{sw}^{\uparrow L}\bef\text{ftn}_{L}\quad.\label{eq:l-interchange-simplify-2}
\end{align}
Simplify the expression $(a\rightarrow\bbnum 0^{:P}+q\times a)^{\uparrow L}\bef\text{sw}^{\uparrow L}$
separately:
\begin{align}
 & (a\rightarrow\bbnum 0^{:P}+q\times a)\bef\text{sw}\nonumber \\
{\color{greenunder}\text{compute composition}:}\quad & =a\rightarrow\gunderline{(\bbnum 0^{:P}+q\times a)\triangleright\text{sw}}\nonumber \\
{\color{greenunder}\text{definition of }\text{sw}:}\quad & =\gunderline{a\rightarrow a\triangleright(}x\rightarrow\bbnum 0^{:P}+q\times x)^{\uparrow L}\nonumber \\
{\color{greenunder}\text{unexpand function}:}\quad & =(x\rightarrow\bbnum 0^{:P}+q\times x)^{\uparrow L}\quad.\label{eq:l-interchange-simplify-3}
\end{align}
Then we continue simplifying Eq.~(\ref{eq:l-interchange-simplify-2}):
\begin{align*}
 & q\times l\rightarrow l\triangleright\gunderline{(a\rightarrow\bbnum 0^{:P}+q\times a)^{\uparrow L}\bef\text{sw}^{\uparrow L}}\bef\text{ftn}_{L}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:l-interchange-simplify-3})}:}\quad & =q\times l\rightarrow l\triangleright\gunderline{(x\rightarrow\bbnum 0^{:P}+q\times x)^{\uparrow L\uparrow L}\bef\text{ftn}_{L}}\\
{\color{greenunder}\text{naturality law of }\text{ftn}_{L}:}\quad & =q\times l\rightarrow l\triangleright\text{ftn}_{L}\bef(x\rightarrow\bbnum 0^{:P}+q\times x)^{\uparrow L}\quad.
\end{align*}
This equals the lower expression in Eq.~(\ref{eq:l-interchange-derivation1})
after renaming the bound variable $x$ to $a$.

\paragraph{The outer interchange law}

We need to show that $\text{ftn}_{M}\bef\text{sw}=\text{sw}^{\uparrow M}\bef\text{sw}\bef\text{ftn}_{M}^{\uparrow L}$.
The left-hand side is written using the matrices for $\text{ftn}_{M}$
and $\text{sw}$:
\begin{align}
 & \text{ftn}_{M}\bef\text{sw}=\,\left\Vert \begin{array}{cc}
\text{id} & \bbnum 0\\
q\times p\rightarrow p & \bbnum 0\\
\bbnum 0 & q_{1}\times q_{2}\times a\rightarrow\left(q_{1}\oplus q_{2}\right)\times a
\end{array}\right|\,\bef\,\left\Vert \begin{array}{c}
(x^{:P}\rightarrow x+\bbnum 0)\bef\text{pu}_{L}\\
q\times l\rightarrow l\triangleright(x\rightarrow\bbnum 0+q\times x)^{\uparrow L}
\end{array}\right|\nonumber \\
 & =\,\,\left\Vert \begin{array}{c}
(x^{:P}\rightarrow x+\bbnum 0)\bef\text{pu}_{L}\\
\left(q\times p\rightarrow p+\bbnum 0\right)\bef\text{pu}_{L}\\
q_{1}\times q_{2}\times a\rightarrow a\triangleright(x\rightarrow\bbnum 0+\left(q_{1}\oplus q_{2}\right)\times x)^{\uparrow L}
\end{array}\right|\quad.\label{eq:m-interchange-law-of-swap-linear-monads-left-hand-side}
\end{align}
We cannot simplify this matrix, so we hope to transform the right-hand
side ($\text{sw}^{\uparrow M}\bef\text{sw}\bef\text{ftn}_{M}^{\uparrow L}$)
to the same matrix. Begin by writing the matrix for $\text{sw}^{\uparrow M}$,
expanding the rows for the input type $M^{M^{L^{A}}}$:
\begin{align*}
 & \text{sw}^{\uparrow M}=\,\begin{array}{|c||cc|}
 & P & Q\times L^{M^{A}}\\
\hline P & \text{id} & \bbnum 0\\
Q\times P & \bbnum 0 & q\times p\rightarrow q\times\text{sw}\left(p+\bbnum 0\right)\\
Q\times Q\times L^{A} & \bbnum 0 & q_{1}\times q_{2}\times l\rightarrow q_{1}\times\text{sw}\left(\bbnum 0+q_{2}\times l\right)
\end{array}\\
 & =\,\begin{array}{||cc|}
\text{id} & \bbnum 0\\
\bbnum 0 & q\times p\rightarrow q\times\text{pu}_{L}\left(p+\bbnum 0\right)\\
\bbnum 0 & q_{1}\times q_{2}\times l\rightarrow q_{1}\times(l\triangleright(x\rightarrow\bbnum 0+q_{2}\times x)^{\uparrow L})
\end{array}\quad.
\end{align*}
Then compute the composition $\text{sw}^{\uparrow M}\bef\text{sw}$:
\begin{align*}
 & \text{sw}^{\uparrow M}\bef\text{sw}=\,\left\Vert \begin{array}{cc}
\text{id} & \bbnum 0\\
\bbnum 0 & q\times p\rightarrow q\times\text{pu}_{L}\left(p+\bbnum 0\right)\\
\bbnum 0 & q_{1}\times q_{2}\times l\rightarrow q_{1}\times(l\triangleright(x\rightarrow\bbnum 0+q_{2}\times x)^{\uparrow L})
\end{array}\right|\,\bef\,\left\Vert \begin{array}{c}
(x^{:P}\rightarrow x+\bbnum 0)\bef\text{pu}_{L}\\
q\times l\rightarrow(l\triangleright(x\rightarrow\bbnum 0+q\times x)^{\uparrow L})
\end{array}\right|\\
 & =\,\,\left\Vert \begin{array}{c}
(x^{:P}\rightarrow x+\bbnum 0)\bef\text{pu}_{L}\\
q\times p\rightarrow\left(p+\bbnum 0\right)\triangleright\text{pu}_{L}\bef(x^{:M^{A}}\rightarrow\bbnum 0^{:P}+q\times x)^{\uparrow L}\\
q_{1}\times q_{2}\times l\rightarrow l\triangleright(x^{:M^{A}}\rightarrow\bbnum 0^{:P}+q_{1}\times x)^{\uparrow L}\bef(x\rightarrow\bbnum 0+q_{2}\times x)^{\uparrow L}
\end{array}\right|
\end{align*}
\begin{align*}
 & =\,\left\Vert \begin{array}{c}
(x^{:P}\rightarrow x+\bbnum 0)\bef\text{pu}_{L}\\
q\times p\rightarrow(\bbnum 0^{:P}+q\times\left(p+\bbnum 0\right))\triangleright\text{pu}_{L}\\
q_{1}\times q_{2}\times l\rightarrow l\triangleright(x^{:M^{A}}\rightarrow\bbnum 0+q_{1}\times(\bbnum 0+q_{2}\times x))^{\uparrow L}
\end{array}\right|\quad.
\end{align*}
Now we need to post-compose $\text{ftn}_{M}^{\uparrow L}$ with this
column:
\begin{align*}
\text{sw}^{\uparrow M}\bef\text{sw}\bef\text{ftn}_{M}^{\uparrow L} & =\,\left\Vert \begin{array}{c}
(x^{:P}\rightarrow x+\bbnum 0)\bef\gunderline{\text{pu}_{L}\bef\text{ftn}_{M}^{\uparrow L}}\\
(q\times p\rightarrow\bbnum 0^{:P}+q\times\left(p+\bbnum 0\right))\bef\gunderline{\text{pu}_{L}\bef\text{ftn}_{M}^{\uparrow L}}\\
q_{1}\times q_{2}\times l\rightarrow l\triangleright(x^{:M^{A}}\rightarrow\bbnum 0+q_{1}\times(\bbnum 0+q_{2}\times x))^{\uparrow L}\bef\text{ftn}_{M}^{\uparrow L}
\end{array}\right|\\
{\color{greenunder}\text{naturality law of }\text{pu}_{L}:}\quad & =\,\,\left\Vert \begin{array}{c}
(x^{:P}\rightarrow x+\bbnum 0)\bef\text{ftn}_{M}\bef\text{pu}_{L}\\
(q\times p\rightarrow\bbnum 0^{:P}+q\times\left(p+\bbnum 0\right))\bef\text{ftn}_{M}\bef\text{pu}_{L}\\
q_{1}\times q_{2}\times l\rightarrow l\triangleright(x^{:M^{A}}\rightarrow\gunderline{\text{ftn}_{M}\left(\bbnum 0+q_{1}\times(\bbnum 0+q_{2}\times x)\right)})^{\uparrow L}
\end{array}\right|\\
{\color{greenunder}\text{compute }\text{ftn}_{M}(...):}\quad & =\,\left\Vert \begin{array}{c}
(x^{:P}\rightarrow\text{ftn}_{M}(x+\bbnum 0))\bef\text{pu}_{L}\\
(q\times p\rightarrow\gunderline{\text{ftn}_{M}(\bbnum 0^{:P}+q\times\left(p+\bbnum 0\right))})\bef\text{pu}_{L}\\
q_{1}\times q_{2}\times l\rightarrow l\triangleright(x^{:M^{A}}\rightarrow\bbnum 0+\left(q_{1}\oplus q_{2}\right)\times x)^{\uparrow L}
\end{array}\right|\\
{\color{greenunder}\text{compute }\text{ftn}_{M}(...):}\quad & =\,\,\left\Vert \begin{array}{c}
(x^{:P}\rightarrow x+\bbnum 0)\bef\text{pu}_{L}\\
(q\times p\rightarrow p+\bbnum 0)\bef\text{pu}_{L}\\
q_{1}\times q_{2}\times l\rightarrow l\triangleright(x^{:M^{A}}\rightarrow\bbnum 0+\left(q_{1}\oplus q_{2}\right)\times x)^{\uparrow L}
\end{array}\right|\quad.
\end{align*}
After renaming $l$ to $a$, this is the same as the column in Eq.~(\ref{eq:m-interchange-law-of-swap-linear-monads-left-hand-side}),
which proves the law.

\paragraph{Monadic naturality laws}

We need to verify the laws of Statement~\ref{subsec:Statement-inside-transformer-swap-laws}:
\[
\text{sw}_{\text{Id},M}=\text{id}\quad,\quad\quad\text{sw}_{L,M}\bef\phi=\phi^{\uparrow M}\bef\text{sw}_{N,M}\quad,\quad\quad\text{sw}_{L,M}\bef\theta^{\uparrow L}=\theta\quad,
\]
for arbitrary monad morphisms $\phi:L\leadsto N$ and $\theta:M\leadsto\text{Id}$.

The first law is the swap identity law, $\text{sw}_{\text{Id},M}=\text{id}$:
\begin{align*}
 & \text{sw}_{\text{Id},M}\\
{\color{greenunder}\text{Eq.~(\ref{eq:single-valued-monad-def-of-swap}) with }L=\text{Id}:}\quad & =\,\begin{array}{|c||c|}
P & (x^{:P}\rightarrow x+\bbnum 0^{:Q\times A})\bef\text{pu}_{\text{Id}}\\
Q\times\text{Id}^{A} & q\times l\rightarrow l\triangleright(a^{:A}\rightarrow\bbnum 0^{:P}+q\times a)^{\uparrow\text{Id}}
\end{array}\\
{\color{greenunder}\text{matrix notation}:}\quad & =\,\,\begin{array}{|c||c|}
P & x^{:P}\rightarrow x+\bbnum 0^{:Q\times A}\\
Q\times A & q\times a\rightarrow\bbnum 0^{:P}+q\times a
\end{array}\,=\text{id}\quad.
\end{align*}

Begin with the left-hand side of the second law:
\begin{align*}
 & \text{sw}_{L,M}\bef\phi\\
{\color{greenunder}\text{definition of }\text{sw}_{L,M}:}\quad & =\,\left\Vert \begin{array}{c}
(x^{:P}\rightarrow x+\bbnum 0^{:Q\times A})\bef\text{pu}_{L}\\
q\times l\rightarrow l\triangleright(a\rightarrow\bbnum 0^{:P}+q\times a)^{\uparrow L}
\end{array}\right|\gunderline{\bef\phi}\\
{\color{greenunder}\text{compose with }\phi:}\quad & =\,\,\left\Vert \begin{array}{c}
(x^{:P}\rightarrow x+\bbnum 0^{:Q\times A})\bef\text{pu}_{L}\bef\phi\\
q\times l\rightarrow l\triangleright\gunderline{(a\rightarrow\bbnum 0^{:P}+q\times a)^{\uparrow L}\bef\phi}
\end{array}\right|\\
{\color{greenunder}\text{naturality law of }\phi:}\quad & =\,\left\Vert \begin{array}{c}
(x^{:P}\rightarrow x+\bbnum 0^{:Q\times A})\bef\text{pu}_{N}\\
q\times l\rightarrow l\triangleright\phi\bef(a\rightarrow\bbnum 0^{:P}+q\times a)^{\uparrow N}
\end{array}\right|\quad.
\end{align*}
The right-hand side is
\begin{align*}
 & \phi^{\uparrow M}\bef\text{sw}_{N,M}=\,\left\Vert \begin{array}{cc}
\text{id} & \bbnum 0\\
\bbnum 0 & q\times l\rightarrow q\times\left(l\triangleright\phi\right)
\end{array}\right|\,\bef\,\left\Vert \begin{array}{c}
(x^{:P}\rightarrow x+\bbnum 0^{:Q\times A})\bef\text{pu}_{N}\\
q\times n\rightarrow n\triangleright(a\rightarrow\bbnum 0^{:P}+q\times a)^{\uparrow N}
\end{array}\right|\\
{\color{greenunder}\text{composition}:}\quad & =\,\,\left\Vert \begin{array}{c}
(x^{:P}\rightarrow x+\bbnum 0^{:Q\times A})\bef\text{pu}_{N}\\
q\times l\rightarrow l\triangleright\phi\bef(a\rightarrow\bbnum 0^{:P}+q\times a)^{\uparrow N}
\end{array}\right|\quad.
\end{align*}
Both sides of the second law are now shown to be equal.

The left-hand side of the third law is
\begin{align}
 & \text{sw}_{L,M}\bef\theta^{\uparrow L}\nonumber \\
{\color{greenunder}\text{compose with }\theta^{\uparrow L}:}\quad & =\,\left\Vert \begin{array}{c}
(x^{:P}\rightarrow x+\bbnum 0^{:Q\times A})\bef\gunderline{\text{pu}_{L}\bef\theta^{\uparrow L}}\\
q\times l\rightarrow l\triangleright(a\rightarrow\bbnum 0^{:P}+q\times a)^{\uparrow L}\bef\theta^{\uparrow L}
\end{array}\right|\nonumber \\
{\color{greenunder}\text{naturality law of }\text{pu}_{L}:}\quad & =\,\,\left\Vert \begin{array}{c}
(x^{:P}\rightarrow x+\bbnum 0^{:Q\times A})\bef\theta\bef\text{pu}_{L}\\
q\times l\rightarrow l\triangleright\big(a\rightarrow\theta(\bbnum 0^{:P}+q\times a)\big)^{\uparrow L}
\end{array}\right|\quad.\label{eq:linear-monads-monadic-naturality-of-swap-2}
\end{align}
We expect this to equal the right-hand side, which we write as
\begin{align}
 & m^{:M^{L^{A}}}\rightarrow\theta(m)\nonumber \\
{\color{greenunder}\text{matrix notation}:}\quad & =\,\left\Vert \begin{array}{c}
x^{:P}\rightarrow\theta(x+\bbnum 0^{:Q\times L^{A}})\\
q\times l\rightarrow\theta(\bbnum 0^{:P}+q\times l)
\end{array}\right|\quad.\label{eq:linear-monads-monadic-naturality-of-swap-1}
\end{align}
Now consider each line in Eq.~(\ref{eq:linear-monads-monadic-naturality-of-swap-2})
separately. The upper line can be transformed as
\begin{align*}
 & (x^{:P}\rightarrow x+\bbnum 0^{:Q\times A})\bef\gunderline{\theta\bef\text{pu}_{L}}\\
{\color{greenunder}\text{naturality law of }\theta:}\quad & =(x^{:P}\rightarrow x+\bbnum 0^{:Q\times A})\bef\gunderline{\text{pu}_{L}^{\uparrow M}}\bef\theta\\
{\color{greenunder}\text{definition of }^{\uparrow M}:}\quad & =x^{:P}\rightarrow\,\left|\begin{array}{cc}
x\enskip & \bbnum 0\end{array}\right|\,\triangleright\,\left\Vert \begin{array}{cc}
\text{id} & \bbnum 0\\
\bbnum 0 & q\times l\rightarrow q\times\text{pu}_{L}(l)
\end{array}\right|\,\bef\theta\\
{\color{greenunder}\text{matrix composition}:}\quad & =x^{:P}\rightarrow(x+\bbnum 0^{:Q\times L^{A}})\triangleright\theta\quad.
\end{align*}
This is now equal to the upper line of Eq.~(\ref{eq:linear-monads-monadic-naturality-of-swap-1}).

To proceed with the proof for the lower line of Eq.~(\ref{eq:linear-monads-monadic-naturality-of-swap-2}),
we need to evaluate the monad morphism $\theta:M^{A}\rightarrow A$
on a specific value of type $M^{A}$ of the form $\bbnum 0+q\times a$.
We note that the value $\theta(\bbnum 0+q\times a)$ must be of type
$A$ and must be computed in the same way for all types $A$, because
$\theta$ is a natural transformation. It seems clear that the result
cannot depend on the value $q^{:Q}$ since $Q$ is a type unrelated
to $A$. In other words, we expect that $\theta(\bbnum 0+q\times a)=a$
as a consequence of naturality of $\theta$. To derive this formally,
we use the trick of starting with a unit type ($\bbnum 1$) and then
mapping it to $A$ within the naturality law. For any values $q^{:Q}$
and $a^{:A}$, we define 
\[
m^{:P+Q\times A}\triangleq\bbnum 0^{:P}+q\times a\quad,\quad\quad m_{1}^{:P+Q\times\bbnum 1}\triangleq\bbnum 0^{:P}+q\times1\quad.
\]
We can compute $m$ from $m_{1}$ if we replace $1$ by $a$ under
the functor $M$. To write this as a formula, define the function
$f^{:\bbnum 1\rightarrow A}$ as $f\triangleq\left(\_\rightarrow a\right)$
using the fixed value $a$. Then we have $m=m_{1}\triangleright f^{\uparrow M}$.
Now we apply both sides of the naturality law $f^{\uparrow M}\bef\theta=\theta\bef f$
to the value $m_{1}$:
\[
m_{1}\triangleright f^{\uparrow M}\bef\theta=m_{1}\triangleright\theta\bef f\quad.
\]
Simplify the left-hand side to
\[
\gunderline{m_{1}\triangleright f^{\uparrow M}}\bef\theta=m\triangleright\theta=\theta(\bbnum 0^{:P}+q\times a)\quad.
\]
Simplify the right-hand side to 
\[
m_{1}\triangleright\theta\bef f=f\left(\theta\left(m_{1}\right)\right)=a\quad,
\]
since the function $f$ always returns $a$. Therefore 
\begin{equation}
\theta(\bbnum 0^{:P}+q\times a)=a\quad.\label{eq:runner-on-linear-monads}
\end{equation}
We can now compute the second line in Eq.~(\ref{eq:linear-monads-monadic-naturality-of-swap-2})
as
\begin{align*}
 & q\times l\rightarrow l\triangleright\big(a\rightarrow\theta(\bbnum 0^{:P}+q\times a)\big)^{\uparrow L}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:runner-on-linear-monads})}:}\quad & =q\times l\rightarrow l\,\gunderline{\triangleright\,\big(a\rightarrow a\big)^{\uparrow L}}=q\times l\rightarrow l\triangleright\text{id}^{\uparrow L}=q\times l\rightarrow l\quad.
\end{align*}
The second line in Eq.~(\ref{eq:linear-monads-monadic-naturality-of-swap-1})
is the same function, namely $q\times l\rightarrow l$.

This concludes the proof of the laws of \lstinline!swap! for linear
monads. It follows that all linear monads have lawful monad transformers
that compose inside the foreign monad.

\subsection{Composition of transformers for linear monads}

We have just shown that any linear monad $M^{A}\triangleq P+Q\times A$
has a \lstinline!swap! function obeying the laws necessary for a
composed-inside transformer. The other type of linear monad is $W^{A}\triangleq Q\times\left(P+A\right)$.
Do we need to show separately that the monad $W$ has a lawful \lstinline!swap!
function? No; instead we may use the stacking property of monad transformers
(see Sections~\ref{subsec:Stacking-two-monads}\textendash \ref{subsec:Stacking-any-number-of-monads}).
The monad $W$ is a functor composition of the \lstinline!Writer!
monad $Q\times A$ with the \lstinline!Either! monad $P+A$, which
is the same as applying the \lstinline!Either! monad\textsf{'}s transformer
to the \lstinline!Writer! monad. Because of the transformer stacking
property, the monad transformer of $W$ works as a composed-inside
transformer.

We can show that the functor composition of any two linear monads
has a composed-inside transformer. Suppose $M_{1}$ and $M_{2}$ are
linear monads, so their transformers are also composed-inside:
\[
T_{M_{1}}^{N}=N\circ M_{1}\quad,\quad\quad T_{M_{2}}^{N}=N\circ M_{2}\quad.
\]
The functor composition of $M_{1}$ and $M_{2}$ can be seen as a
monad stack,
\[
M_{1}\circ M_{2}=T_{M_{2}}^{M_{1}}\quad.
\]
What is the transformer for the monad $M_{1}\circ M_{2}$? For any
foreign monad $N$, we have the monad stack
\[
T_{M_{2}}^{T_{M_{1}}^{N}}=T_{M_{2}}^{N\circ M_{1}}=N\circ\left(M_{1}\circ M_{2}\right)\quad.
\]
This is a lawful monad transformer, as we have seen in Section~\ref{subsec:Stacking-two-monads}.
So, this is the transformer for $M_{1}\circ M_{2}$, and it is of
the composed-inside kind.

\section{Composed-outside transformers for rigid monads\label{sec:transformers-rigid-monads}}

Section~\ref{sec:transformers-linear-monads} shows that the composed-inside
transformers are available for monads\index{monads!linear} of the
form $M^{A}=P+Q\times A$ and $M^{A}=Q\times\left(P+A\right)$, called
\textsf{``}linear\textsf{''}. No other examples of composed-inside transformers are
known. It turns out that the composed-\emph{outside} transformers
are available for a significantly wider range of monads. Those monads
are called \textsf{``}rigid\textsf{''} in this book\footnote{Monads of this kind do not seem to have an already accepted name.}
because one of their general properties is having a single, fixed
\textsf{``}data shape\textsf{''} (Statement~\ref{subsec:Statement-rigid-functor-wrapped-unit-is-unit}
below).\index{monads!rigid} 

\paragraph{Definition}

A monad $R$ is \textbf{rigid} if it has a lawful composed-outside
monad transformer, $T_{R}^{M}=R\circ M$, where $M$ is a foreign
monad. 

This definition states the required properties but does not explain
which monads are rigid (or how to recognize a non-rigid monad). We
will answer these questions below.

Two examples of rigid monads are the \lstinline!Reader! monad and
the \lstinline!Sel! (selector)\index{monads!Sel (selector) monad@\texttt{Sel} (selector) monad}
monad,\footnote{See \href{http://math.andrej.com/2008/11/21/}{http://math.andrej.com/2008/11/21/}}
\begin{align*}
\text{(the \texttt{Reader} monad)} & :\quad\quad R^{A}\triangleq Z\rightarrow A\quad,\\
\text{(the \texttt{Sel} monad)} & :\quad\quad S^{A}\triangleq\left(A\rightarrow Z\right)\rightarrow A\quad,
\end{align*}
where $Z$ is a fixed type. These monads have composed-outside transformers:
\begin{align*}
\text{(the \texttt{ReaderT} transformer)} & :\quad\quad T_{R}^{M,A}\triangleq Z\rightarrow M^{A}\quad,\\
\text{(the \texttt{SelT} transformer)} & :\quad\quad T_{S}^{M,A}\triangleq(M^{A}\rightarrow Z)\rightarrow M^{A}\quad.
\end{align*}
To build intuition for rigid monads, we will perform structural analysis
looking for general constructions that create new rigid monads or
combine existing rigid monads into new ones. In this section, we will
prove that the following three constructions produce rigid monads:
\begin{enumerate}
\item \textsf{``}Product\textsf{''}: $P^{A}\times R^{A}$ is a rigid monad if $P$ and $R$
are rigid monads.
\item \textsf{``}Composition\textsf{''}: $P\circ R$ is a rigid monad if $P$ and $R$ are
rigid monads.
\item \textsf{``}Choice\textsf{''}: $C^{A}\triangleq H^{A}\rightarrow A$ is a rigid monad
if $H$ is any contrafunctor.
\end{enumerate}
It is not known whether these constructions are the only possible
ways of creating new rigid monads. Other open questions about rigid
monads are listed in Problem~\ref{par:Problem-monads-3}.

\subsection{Rigid monad construction 1 (product)}

\subsubsection{Statement \label{subsec:Statement-product-rigid-monads}\ref{subsec:Statement-product-rigid-monads}}

The product of rigid monads, $R_{1}^{A}\times R_{2}^{A}$, is a rigid
monad.

\subparagraph{Proof}

If we show that $R_{1}^{A}\times R_{2}^{A}$ has a composed-outside
transformer, it will follow (by definition) that $R_{1}^{A}\times R_{2}^{A}$
is a rigid monad. It follows from Statement~\ref{subsec:Statement-product-of-monad-transformers}
(whose proof does not depend on any of the results of this section)
that a lawful monad transformer $T^{M,A}$ for the product monad $R_{1}^{A}\times R_{2}^{A}$
is the product of transformers : for any foreign monad $M$,
\[
T_{R_{1}}^{M,A}\times T_{R_{2}}^{M,A}=R_{1}^{M^{A}}\times R_{2}^{M^{A}}\quad.
\]
This is the required composed-outside transformer for the monad $R_{1}^{A}\times R_{2}^{A}$.

\subsection{Rigid monad construction 2 (composition)}

Functor composition is the second construction that produces rigid
monads. This is a consequence of the properties of monad transformer
stacks.

\subsubsection{Statement \label{subsec:Statement-composition-rigid-monads}\ref{subsec:Statement-composition-rigid-monads}}

The composition $R_{1}^{R_{2}^{\bullet}}$ of two rigid monads $R_{1}$
and $R_{2}$ is also a rigid monad.

\subparagraph{Proof}

Since $R_{1}$ is rigid, its outside-composition $R_{1}\circ M$ with
any other monad $M$ is a monad. So $R_{1}\circ R_{2}$ is a monad.
To show that $R_{1}\circ R_{2}$ is a rigid monad, we need to show
that its monad transformer is of the composed-outside kind. By Statement~\ref{subsec:Stacking-two-monads},
the stacking of monad transformers $T_{R_{1}}$and $T_{R_{2}}$ is
a lawful monad transformer. Since the transformers for $R_{1}$ and
$R_{2}$ are of the composed-outside kind, $T_{R_{1}}^{M}=R_{1}\circ M$
and $T_{R_{2}}^{M}=R_{2}\circ M$, the stack of transformers is expressed
as
\[
T_{R_{1}}^{T_{R_{2}}^{M}}=R_{1}\circ T_{R_{2}}^{M}=R_{1}\circ(R_{2}\circ M)=R_{1}\circ R_{2}\circ M\quad.
\]
Therefore $T^{M}\triangleq R_{1}\circ R_{2}\circ M$ is a lawful monad
transformer applied to the foreign monad $M$. This shows, by definition
of a rigid monad, that $R_{1}\circ R_{2}$ is a rigid monad.

\subsubsection{Example \label{subsec:Example-rigid-composition-1}\ref{subsec:Example-rigid-composition-1}}

Consider the functor composition of the \lstinline!Sel! monad $R_{1}^{A}\triangleq\left(A\rightarrow Q\right)\rightarrow A$
and the \lstinline!Reader! monad $R_{2}^{A}\triangleq Z\rightarrow A$:
\[
P^{A}\triangleq((Z\rightarrow A)\rightarrow Q)\rightarrow Z\rightarrow A\quad.
\]
It follows from Statement~\ref{subsec:Statement-composition-rigid-monads}
that the functor $P$ is a rigid monad; so $P$\textsf{'}s transformer is of
the composed-outside kind. The the transformed monad for any foreign
monad $M$ is 
\[
T^{A}\triangleq((Z\rightarrow M^{A})\rightarrow Q)\rightarrow Z\rightarrow M^{A}\quad.
\]
To define the monad methods for $T$, we need to have the definitions
of the transformers $T_{R_{1}}^{M}$ and $T_{R_{2}}^{M}$. Since both
the \lstinline!Sel! and the \lstinline!Reader! monads are special
cases of the \lstinline!Choice! monad construction (Section~\ref{subsec:Rigid-monad-construction-1-choice})
where the contrafunctor $H$ is chosen to be $H^{A}\triangleq A\rightarrow Q$
and $H^{A}\triangleq Z$ respectively, we can use Eq.~(\ref{eq:rigid-monad-flm-T-def})
to define the \lstinline!flatMap! methods for the transformers $T_{R_{1}}^{M}$
and $T_{R_{2}}^{M}$:
\begin{lstlisting}
type R1[A] = (A => Q) => A
def map_R1[A, B](r1: R1[A])(f: A => B): R1[B] = { (b2q: B => Q) => f(r1(f andThen b2q)) }
def flatMap_R1[A, B, M[_]: Monad](r1: R1[M[A]])(f: A => R1[M[B]]): R1[M[B]] = {
  (q: M[B] => Q) => map_R1(r1){ (m: M[A]) => m.flatMap(x => f(x)(q)) }(q)
}

type R2[A] = Z => A
def map_R2[A, B](r2: R2[A])(f: A => B): R2[B] = { r2 andThen f }
def flatMap_R2[A, B, M[_]: Monad](r2: R2[M[A]])(f: A => R2[M[B]]): R2[M[B]] = {
  z => map_R2(r2){ (m: M[A]) => m.flatMap(x => f(x)(z)) }(z)
}   
\end{lstlisting}
Now we can define the \lstinline!flatMap! method for $T$ by using
the monad $T_{R_{2}}^{M}$ instead of $M$ in the \lstinline!flatMap!
method for $T_{R_{1}}^{M}$:
\begin{lstlisting}
type T[A] = R1[R2[A]]
def flatMap_T[A, B, M[_]: Monad](t: T[M[A]])(f: A => T[M[B]]): T[M[B]] = {
  (q: R2[M[B]] => Q) => map_R1(t){ (m: R2[M[A]]) => flatMap_R2(m)(x => f(x)(q)) }(q)
}
\end{lstlisting}


\subsection{Rigid monad construction 3 (choice)\label{subsec:Rigid-monad-construction-1-choice}}

The construction called \index{monads!choice monad}the \textbf{choice}
monad, $R^{A}\triangleq H^{A}\rightarrow A$, defines a rigid monad
$R$ for any given contrafunctor $H$. This monad somehow \textsf{``}chooses\textsf{''}
a value of type $A$. The contrafunctor $H$ may \emph{consume} values
of type $A$ (and could check some conditions on those values). For
example, $H$ could be a constant contrafunctor ($H^{A}\triangleq Q$),
a function ($H^{A}\triangleq A\rightarrow Q$), or a more complicated
contrafunctor.

Different contrafunctors $H$ give various rigid monads such as $R^{A}\triangleq\bbnum 1$
(the unit monad), $R^{A}\triangleq A$ (the identity monad), $R^{A}\triangleq Z\rightarrow A$
(the \lstinline!Reader!), and $\text{Sel}^{Q,A}\triangleq\left(A\rightarrow Q\right)\rightarrow A$
(the selector monad). 

The selector monad represents the effect of somehow \textsf{``}selecting\textsf{''}
a value of type $A$ using a function of type $A\rightarrow Q$. A
simple example of a selector monad is found by setting $Q\triangleq\bbnum 2$
(where $\bbnum 2$ denotes the \lstinline!Boolean! type). One may
implement a function of type $\left(A\rightarrow\bbnum 2\right)\rightarrow A$
that \emph{somehow} finds a value of type $A$ that might satisfy
the given predicate of type $A\rightarrow\bbnum 2$. The intention
is to return, if possible, a value that satisfies the predicate. If
no such value can be found, some value of type $A$ is still returned.

A closely related monad is the \textbf{search} \textbf{monad}\index{monads!Search monad@\texttt{Search} monad},
$\text{Search}^{Q,A}\triangleq\left(A\rightarrow\bbnum 1+P\right)\rightarrow\bbnum 1+A$.
This (non-rigid) monad returns an empty value $1+\bbnum 0^{:A}$ if
no value satisfing the \textsf{``}predicate\textsf{''} (a function of type $A\rightarrow\bbnum 1+P$)
is found. There is a mapping from the selector monad to the search
monad, implemented by checking whether the value returned by the selector
monad does actually satisfy the predicate. However, that mapping is
not a monad morphism (Exercise~\ref{subsec:Statement-search-and-selector-monads}).

The selector monad is superficially similar to the continuation monad,
and there is a monad morphism in one direction (Exercise~\ref{subsec:Exercise-selector-and-continuation-monads}).

Assume that $H$ is a contrafunctor and $M$ is a monad, and denote
for brevity 
\[
R^{A}\triangleq H^{A}\rightarrow A\quad,\quad\quad T^{A}\triangleq R^{M^{A}}=H^{M^{A}}\rightarrow M^{A}\quad.
\]
Let us now implement a suitable \lstinline!swap! function and verify
its laws. Then the results of Section~\ref{sec:Monad-transformers-that-use-composition}
will ensure that $T$ is a lawful monad transformer. 

\subsubsection{Statement \label{subsec:Statement-choice-monad-definition-of-flm}\ref{subsec:Statement-choice-monad-definition-of-flm}}

The \lstinline!swap! function and the monad methods for $T$ can
be written as
\begin{align}
 & \text{sw}_{R,M}:M^{R^{A}}\rightarrow R^{M^{A}}\quad,\quad\quad\text{sw}_{R,M}\triangleq m^{:M^{R^{A}}}\rightarrow q^{:H^{M^{A}}}\rightarrow m\triangleright(r\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\bef r)^{\uparrow M}\quad,\label{eq:rigid-monad-short-formula-for-swap}\\
 & \text{pu}_{T}:A\rightarrow H^{M^{A}}\rightarrow M^{A}\quad,\quad\quad\text{pu}_{T}\triangleq\text{pu}_{M}\bef\text{pu}_{R}=a^{:A}\rightarrow\_^{:H^{M^{A}}}\rightarrow\text{pu}_{M}(a)\quad,\nonumber \\
 & \text{ftn}_{T}\triangleq t^{:T^{T^{A}}}\rightarrow k^{:H^{M^{A}}}\rightarrow k\triangleright\big(t\triangleright(\text{flm}_{M}(r^{:R^{M^{A}}}\rightarrow r(k)))^{\uparrow R}\big)=\text{flm}_{R}\left(t\rightarrow q\rightarrow t\triangleright\text{flm}_{M}(r\rightarrow r(q))\right)\quad,\nonumber \\
 & \text{flm}_{T}(f)=\text{flm}_{R}\big(y\rightarrow q\rightarrow y\triangleright\text{flm}_{M}(x\rightarrow q\triangleright(x\triangleright f))\big)\label{eq:rigid-monad-def-flm-t-via-flm-r}\\
 & \quad=t^{:R^{M^{A}}}\rightarrow q^{:H^{M^{B}}}\rightarrow q\triangleright\big(t\triangleright\big(\text{flm}_{M}(x^{:A}\rightarrow q\triangleright(x\triangleright f))\big)^{\uparrow R}\big)\quad.\label{eq:rigid-monad-flm-T-def}
\end{align}
The monad $R$\textsf{'}s methods may be defined by
\begin{align}
 & \text{pu}_{R}:A\rightarrow H^{A}\rightarrow A\quad,\quad\quad\text{pu}_{R}\triangleq a\rightarrow\_^{:H^{A}}\rightarrow a\quad,\nonumber \\
 & \text{ftn}_{R}:(H^{H^{A}\rightarrow A}\rightarrow A\big)\rightarrow H^{A}\rightarrow A\quad,\quad\quad\text{ftn}_{R}\triangleq r^{:R^{R^{A}}}\rightarrow k^{:H^{A}}\rightarrow r\triangleright(q^{:R^{A}}\rightarrow q(k))^{\uparrow R}\quad,\nonumber \\
 & \text{flm}_{R}(g^{:A\rightarrow R^{B}})\triangleq r^{:R^{A}}\rightarrow k^{:H^{B}}\rightarrow k\triangleright\big(r\triangleright(a^{:A}\rightarrow g(a)(k))^{\uparrow R}\big)\quad.\label{eq:rigid-monad-flm-R-def}
\end{align}


\subparagraph{Proof}

We begin by deriving the code for the \lstinline!swap! function.
The monad $T$\textsf{'}s methods depend on the monad $R$, whose code we will
need to write next. Finally, we will obtain alternative formulas for
$\text{flm}_{T}$ and $\text{flm}_{R}$ that will be useful in derivations. 

\paragraph{The code for \texttt{swap}}

Throughout the proof, we assume $M$ to be a fixed, lawful monad.
Begin implementing \lstinline!swap! by using typed holes:
\[
\text{sw}_{R,M}:M^{R^{A}}\rightarrow H^{M^{A}}\rightarrow M^{A}\quad,\quad\quad\text{sw}_{R,M}\triangleq m^{:M^{H^{A}\rightarrow A}}\rightarrow q^{:H^{M^{A}}}\rightarrow\text{???}^{:M^{A}}\quad.
\]
Since the monad $M$ is arbitrary and no values of type $A$ are given,
the only way of computing a value of type $M^{A}$ is by using the
given value $m$. We could transform $m:M^{H^{A}\rightarrow A}$ to
a value of type $M^{A}$ if we could transform a value of type $H^{A}\rightarrow A$
into a value of type $A$:
\[
\text{sw}_{R,M}\triangleq m^{:M^{H^{A}\rightarrow A}}\rightarrow q^{:H^{M^{A}}}\rightarrow m\triangleright\big(r^{:H^{A}\rightarrow A}\rightarrow\text{???}^{:A}\big)^{\uparrow M}\quad.
\]
Lacking any given values of type $A$, we have to apply $r$ to a
value of type $H^{A}$:
\[
\text{sw}_{R,M}\triangleq m^{:M^{H^{A}\rightarrow A}}\rightarrow q^{:H^{M^{A}}}\rightarrow m\triangleright\big(r^{:H^{A}\rightarrow A}\rightarrow r(\text{???}^{:H^{A}})\big)^{\uparrow M}\quad.
\]
We have a value $q:H^{M^{A}}$ and a method $\text{pu}_{M}:A\rightarrow M^{A}$.
This gives us the solution:
\[
\text{sw}_{R,M}\triangleq m^{:M^{H^{A}\rightarrow A}}\rightarrow q^{:H^{M^{A}}}\rightarrow m\triangleright\big(r^{:H^{A}\rightarrow A}\rightarrow r(q\triangleright\text{pu}_{M}^{\downarrow H})\big)\quad.
\]
Rewrite the formula in the $\triangleright$-notation to obtain Eq.~(\ref{eq:rigid-monad-short-formula-for-swap}):
\[
\text{sw}_{R,M}:M^{R^{A}}\rightarrow R^{M^{A}}\quad,\quad\quad\text{sw}_{R,M}\triangleq m^{:M^{R^{A}}}\rightarrow q^{:H^{M^{A}}}\rightarrow m\triangleright(r\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\bef r)^{\uparrow M}\quad.
\]
Equivalently, we may write
\begin{equation}
q\triangleright\big(m\triangleright\text{sw}_{R,M}\big)=m\triangleright(r\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\bef r)^{\uparrow M}\quad.\label{eq:rigid-monad-choice-swap-short}
\end{equation}
We will use these formulas for \lstinline!swap! in proofs of its
various laws.

\paragraph{The code for the monad $R$}

We now derive the code for the monad $R$\textsf{'}s methods. That monad\textsf{'}s
laws were proved in Statement~\ref{subsec:Statement-monad-construction-2}
using flipped types of Kleisli morphisms and the flipped Kleisli composition
($\tilde{\diamond}_{_{R}}$). To restore the standard type signatures
for \lstinline!pure! and \lstinline!flatMap!, we begin by flipping
the arguments of $\tilde{\text{pu}}_{R}$:
\begin{align*}
{\color{greenunder}\text{use Eq.~(\ref{eq:def-of-pure-for-exp-construction-h-a-a})}:}\quad & \text{pu}_{R}\triangleq\text{flip}(\tilde{\text{pu}}_{R})=\text{flip}(\_^{:H^{A}}\rightarrow a^{:A}\rightarrow a)=a^{:A}\rightarrow\_^{:H^{A}}\rightarrow a\quad.
\end{align*}
To recover the Kleisli composition ($\diamond_{_{R}}$), we need to
flip both arguments of $\tilde{\diamond}_{_{R}}$:
\begin{align*}
 & f^{:A\rightarrow H^{B}\rightarrow B}\diamond_{_{R}}g^{:B\rightarrow H^{C}\rightarrow C}\triangleq\text{flip}\big(\text{flip}(f)\,\tilde{\diamond}_{_{R}}\text{flip}(g)\big)\\
{\color{greenunder}\text{use Eq.~(\ref{eq:def-of-Kleisli-for-exp-construction-h-a-a})}:}\quad & =\text{flip}\big(k^{:H^{C}}\rightarrow\tilde{f}\big(k\triangleright(\tilde{g}(k))^{\downarrow H}\big)\bef\tilde{g}(k)\big)\\
{\color{greenunder}\text{expand function}:}\quad & =\text{flip}\big(k^{:H^{C}}\rightarrow a^{:A}\rightarrow a\triangleright\tilde{f}\big(k\triangleright(\tilde{g}(k))^{\downarrow H}\big)\bef\tilde{g}(k)\big)\\
{\color{greenunder}\text{definition of }\text{flip}:}\quad & =a^{:A}\rightarrow k^{:H^{C}}\rightarrow a\triangleright\tilde{f}\big(k\triangleright(\tilde{g}(k))^{\downarrow H}\big)\bef\tilde{g}(k)\quad,
\end{align*}
where the flipped versions of the functions $f$ and $g$ are defined
by
\begin{align*}
 & \tilde{f}:H^{B}\rightarrow A\rightarrow B\quad,\quad\quad\tilde{f}\triangleq h^{:H^{B}}\rightarrow a^{:A}\rightarrow f(a)(h)\quad,\quad\quad a\triangleright\tilde{f}(h)=f(a)(h)\quad,\\
 & \tilde{g}:H^{C}\rightarrow B\rightarrow C\quad,\quad\quad\tilde{g}\triangleq h^{:H^{C}}\rightarrow b^{:B}\rightarrow g(b)(h)\quad,\quad\quad b\triangleright\tilde{g}(h)=g(b)(h)\quad.
\end{align*}
Substituting these definitions, we compute:
\begin{align*}
 & f\diamond_{_{R}}g=a^{:A}\rightarrow k^{:H^{C}}\rightarrow a\triangleright\tilde{f}\big(k\triangleright(\tilde{g}(k))^{\downarrow H}\big)\,\gunderline{\bef}\,\tilde{g}(k)\\
{\color{greenunder}\triangleright\text{-notation}:}\quad & =a\rightarrow k\rightarrow a\triangleright\gunderline{\tilde{f}}\big(k\triangleright(\tilde{g}(k))^{\downarrow H}\big)\triangleright\tilde{g}(k)\\
 & =a\rightarrow k\rightarrow f(a)(k\,\gunderline{\triangleright(\tilde{g}(k)})^{\downarrow H})\,\gunderline{\triangleright\tilde{g}(k)}=a\rightarrow k\rightarrow g\big(f(a)(k\triangleright(b\rightarrow g(b)(k))^{\downarrow H})\big)(k)\quad.
\end{align*}
This code can be shortened by defining a helper function $\gamma(g,k)$,
also denoted $\gamma_{g,k}$ for brevity:
\begin{align*}
 & \gamma_{g,k}:B\rightarrow C\quad,\quad\quad\gamma_{g,k}\triangleq b\rightarrow g(b)(k)=\tilde{g}(k)\quad,\\
{\color{greenunder}\text{then write}:}\quad & f\diamond_{_{R}}g=a^{:A}\rightarrow k^{:H^{C}}\rightarrow f(a)(k\triangleright\gamma_{g,k}^{\downarrow H})\triangleright\gamma_{g,k}\quad.
\end{align*}
The next step is to derive the code for $\text{flm}_{R}$:
\begin{align*}
 & \text{flm}_{R}(g^{:A\rightarrow R^{B}})\triangleq\text{id}^{:R^{A}\rightarrow R^{A}}\diamond_{_{R}}g=r^{:R^{A}}\rightarrow k^{:H^{B}}\rightarrow\text{id}(r)(k\triangleright\gamma_{g,k}^{\downarrow H})\triangleright\gamma_{g,k}\\
 & =r\rightarrow k\rightarrow r(k\triangleright\gamma_{g,k}^{\downarrow H})\triangleright\gamma_{g,k}=r\rightarrow k\rightarrow g\big(r(k\triangleright(b\rightarrow g(b)(k))^{\downarrow H})\big)(k)\quad.
\end{align*}
Finally, we find $\text{ftn}_{R}$ as
\[
\text{ftn}_{R}\triangleq\text{flm}_{R}(\text{id}^{:R^{A}\rightarrow R^{A}})=r^{:R^{R^{A}}}\rightarrow k^{:H^{A}}\rightarrow r(k\triangleright(q^{:R^{A}}\rightarrow q(k))^{\downarrow H})\big)(k)\quad.
\]

The last two formulas may be shortened if we notice that the lifting
to $R$ is expressed as
\[
f^{\uparrow R}=r^{:H^{A}\rightarrow A}\rightarrow k^{:H^{B}}\rightarrow f(r(k\triangleright f^{\downarrow H}))=r^{:R^{A}}\rightarrow f^{\downarrow H}\bef r\bef f\quad.
\]
So, we may equivalently write the code for $\text{flm}_{R}$ and $\text{ftn}_{R}$
as
\[
\text{flm}_{R}(g^{:A\rightarrow R^{B}})\triangleq r^{:R^{A}}\rightarrow k^{:H^{B}}\rightarrow k\triangleright\big(r\triangleright\gamma_{g,k}^{\uparrow R}\big)\quad,\quad\text{ftn}_{R}\triangleq r^{:R^{R^{A}}}\rightarrow k^{:H^{B}}\rightarrow k\triangleright\big(r\triangleright(q^{:R^{A}}\rightarrow q(k))^{\uparrow R}\big)\quad.
\]
This corresponds to Eq.~(\ref{eq:rigid-monad-flm-R-def}).

\paragraph{Deriving $\text{ftn}_{T}$ from $\text{sw}_{R,M}$}

Given the code of \lstinline!swap! defined by Eq.~(\ref{eq:rigid-monad-short-formula-for-swap}),
we can recover the code of $\text{ftn}_{T}$ by using Eq.~(\ref{eq:define-flatten-via-swap}),
where we need to use the monad $R$ instead of $L$:
\begin{align}
 & \text{ftn}_{T}=\gunderline{\text{sw}^{\uparrow R}\bef\text{ftn}_{R}}\bef\text{ftn}_{M}^{\uparrow R}=\text{flm}_{R}(\text{sw})\bef\text{ftn}_{M}^{\uparrow R}\nonumber \\
{\color{greenunder}\text{naturality law of }\text{flm}_{R}:}\quad & =\text{flm}_{R}(\text{sw}\bef\text{ftn}_{M}^{\uparrow R})\quad.\label{eq:rigid-monad-ftn-derivation-4a}
\end{align}
To proceed, we need to simplify $\text{sw}\bef\text{ftn}_{M}^{\uparrow R}$:
\begin{align}
 & \text{sw}\bef\text{ftn}_{M}^{\uparrow R}\nonumber \\
{\color{greenunder}\text{definitions}:}\quad & =\big(m\rightarrow q\rightarrow m\triangleright\big((r\rightarrow\gunderline q\triangleright\text{pu}_{M}^{\downarrow H}\bef r)\big)^{\uparrow M}\big)\bef(\gunderline{r\rightarrow\text{ftn}_{M}^{\downarrow H}\bef r\bef\text{ftn}_{M}})\nonumber \\
{\color{greenunder}\text{composition}:}\quad & =m\rightarrow\gunderline{\text{ftn}_{M}^{\downarrow H}}\bef\big(q\rightarrow m\triangleright\big((r\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\bef r)\big)^{\uparrow M}\big)\bef\text{ftn}_{M}\nonumber \\
{\color{greenunder}\text{expansion}:}\quad & =m\rightarrow\big(q\rightarrow\gunderline{q\triangleright\text{ftn}_{M}^{\downarrow H}}\big)\bef\big(q\rightarrow m\triangleright\big((r\rightarrow\gunderline q\triangleright\text{pu}_{M}^{\downarrow H}\bef r)\big)^{\uparrow M}\big)\bef\text{ftn}_{M}\nonumber \\
{\color{greenunder}\text{composition}:}\quad & =m\rightarrow\big(q\rightarrow m\triangleright\big((r\rightarrow\gunderline{q\triangleright\text{ftn}_{M}^{\downarrow H}\triangleright\text{pu}_{M}^{\downarrow H}}\bef r)\big)^{\uparrow M}\big)\bef\text{ftn}_{M}\quad.\label{eq:rigid-monad-swap-ftn-derivation4}
\end{align}
We can transform the sub-expression $(r\rightarrow q\triangleright\text{ftn}_{M}^{\downarrow H}\triangleright\text{pu}_{M}^{\downarrow H}\bef r)$
to
\begin{align}
{\color{greenunder}\triangleright\text{-notation}:}\quad & r\rightarrow q\triangleright\gunderline{\text{ftn}_{M}^{\downarrow H}\bef\text{pu}_{M}^{\downarrow H}}\bef r\nonumber \\
{\color{greenunder}\text{composition law of }H:}\quad & =r\rightarrow q\triangleright(\gunderline{\text{pu}_{M}\bef\text{ftn}_{M}})^{\downarrow H}\bef r\nonumber \\
{\color{greenunder}\text{left identity law of }M:}\quad & =r\rightarrow\gunderline{q\triangleright r}=r\rightarrow r(q)\quad.\label{eq:rigid-monad-swap-ftn-derivation5}
\end{align}
Using this simplification, we continue transforming Eq.~(\ref{eq:rigid-monad-swap-ftn-derivation4}):
\begin{align*}
 & \text{sw}\bef\text{ftn}_{M}^{\uparrow R}=m\rightarrow\big(q\rightarrow m\triangleright\big((r\rightarrow\gunderline{q\triangleright\text{ftn}_{M}^{\downarrow H}\triangleright\text{pu}_{M}^{\downarrow H}\bef r})\big)^{\uparrow M}\big)\bef\text{ftn}_{M}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:rigid-monad-swap-ftn-derivation5})}:}\quad & =m\rightarrow\gunderline{\big(}q\rightarrow m\triangleright(r\rightarrow r(q))^{\uparrow M}\gunderline{\big)\bef}\text{ftn}_{M}\\
{\color{greenunder}\text{composition}:}\quad & =m\rightarrow q\rightarrow m\triangleright(r\rightarrow r(q)\gunderline{)^{\uparrow M}\bef\text{ftn}_{M}}=m\rightarrow q\rightarrow m\triangleright\text{flm}_{M}\left(r\rightarrow r(q)\right)\quad.
\end{align*}
It follows that
\begin{equation}
(\text{sw}\bef\text{ftn}_{M}^{\uparrow R})(x)(y)=x\triangleright\text{flm}_{M}(r\rightarrow r(y))\quad.\label{eq:rigid-monad-swap-ftn-derivation6}
\end{equation}
Now we rewrite Eq.~(\ref{eq:rigid-monad-ftn-derivation-4a}) and
get:
\begin{align*}
 & \text{ftn}_{T}=\text{flm}_{R}(\text{sw}\bef\text{ftn}_{M}^{\uparrow R})\\
{\color{greenunder}\text{use Eq.~(\ref{eq:rigid-monad-flm-R-def})}:}\quad & =t\rightarrow k\rightarrow k\triangleright\big(t\triangleright(a\rightarrow(\gunderline{\text{sw}\bef\text{ftn}_{M}^{\uparrow R}})(a)(k))^{\uparrow R}\big)\\
{\color{greenunder}\text{use Eq.~(\ref{eq:rigid-monad-swap-ftn-derivation6})}:}\quad & =t\rightarrow k\rightarrow k\triangleright\big(t\triangleright(\gunderline{a\rightarrow a\,\triangleright}\,\text{flm}_{M}(r\rightarrow r(k)))^{\uparrow R}\big)\\
{\color{greenunder}\text{unexpand function}:}\quad & =t\rightarrow k\rightarrow k\triangleright\big(t\triangleright(\text{flm}_{M}(r\rightarrow r(k)))^{\uparrow R}\big)\quad.
\end{align*}
It is sometimes convenient to express the code of $\text{ftn}_{T}$
in terms of $\text{flm}_{R}$:
\[
\text{ftn}_{T}=\text{flm}_{R}(\text{sw}\bef\text{ftn}_{M}^{\uparrow R})=\text{flm}_{R}\big(m\rightarrow q\rightarrow m\triangleright\text{flm}_{M}\left(r\rightarrow r(q)\right)\big)\quad.
\]


\paragraph{Deriving $\text{flm}_{T}$ from $\text{ftn}_{T}$}

We use the formula for $\text{ftn}_{T}$ just derived above:
\begin{align*}
 & \text{flm}_{T}(g)=g^{\uparrow T}\bef\gunderline{\text{ftn}_{T}}=\gunderline{g^{\uparrow M\uparrow R}\bef\text{flm}_{R}}\big(m\rightarrow q\rightarrow m\triangleright\text{flm}_{M}\left(r\rightarrow r(q)\right)\big)\\
{\color{greenunder}\text{left naturality law of }\text{flm}_{R}:}\quad & =\text{flm}_{R}\big(\gunderline{g^{\uparrow M}\bef(m}\rightarrow q\rightarrow m\triangleright\text{flm}_{M}\left(r\rightarrow r(q)\right))\big)\\
{\color{greenunder}\text{compute composition}:}\quad & =\text{flm}_{R}\big(m\rightarrow q\rightarrow m\triangleright\gunderline{g^{\uparrow M}\triangleright\text{flm}_{M}}\left(r\rightarrow r(q)\right)\big)\\
{\color{greenunder}\text{naturality law of }\text{flm}_{M}:}\quad & =\text{flm}_{R}\big(m\rightarrow q\rightarrow m\triangleright\text{flm}_{M}\big(\gunderline{g\bef(r\rightarrow r(q))}\big)\big)\\
{\color{greenunder}\text{compute composition}:}\quad & =\text{flm}_{R}\big(m\rightarrow q\rightarrow m\triangleright\text{flm}_{M}\big(r\rightarrow g(r)(q))\big)\big)\\
{\color{greenunder}\text{obtain Eq.~(\ref{eq:rigid-monad-def-flm-t-via-flm-r})}:}\quad & =\text{flm}_{R}\big(m\rightarrow q\rightarrow m\triangleright\text{flm}_{M}(\gamma_{g,q})\big)\quad.
\end{align*}

This concludes the derivation of the formulas listed in Statement~\ref{subsec:Statement-choice-monad-definition-of-flm}.

\subsubsection{Statement \label{subsec:Statement-choice-monad-swap}\ref{subsec:Statement-choice-monad-swap}}

The function \lstinline!swap! (short notation $\text{sw}_{R,M}$)
defined in Eq.~(\ref{eq:rigid-monad-short-formula-for-swap}) satisfies
the four laws of Statement~\ref{sec:Statement-swap-laws-to-monad-transformer-first-law}
and the monadic naturality laws of Statement~\ref{subsec:Statement-outside-transformer-swap-laws}.

\subparagraph{Proof}

We will verify each of the laws in turn.

\paragraph{The inner identity law}

is $\text{pu}_{R}^{\uparrow M}\bef\text{sw}=\text{pu}_{R}$. To verify
this law, compute:
\begin{align}
{\color{greenunder}\text{expect to equal }\text{pu}_{R}:}\quad & \text{pu}_{R}^{\uparrow M}\bef\gunderline{\text{sw}}\nonumber \\
{\color{greenunder}\text{use Eq.~(\ref{eq:rigid-monad-short-formula-for-swap})}:}\quad & =\big(m\rightarrow\gunderline{m\triangleright\text{pu}_{R}^{\uparrow M}}\big)\bef\big(m\rightarrow q\rightarrow\gunderline m\triangleright\big(r\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\bef r\big)^{\uparrow M}\big)\nonumber \\
{\color{greenunder}\text{function composition}:}\quad & =m\rightarrow q\rightarrow m\triangleright\gunderline{\text{pu}_{R}^{\uparrow M}\bef\big(r\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\bef r\big)^{\uparrow M}}\nonumber \\
{\color{greenunder}\text{composition under }^{\uparrow M}:}\quad & =m\rightarrow q\rightarrow m\triangleright\big(\text{pu}_{R}\bef\big(r\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\bef r\big)\big)^{\uparrow M}\quad.\label{eq:swap-laws-derivation1a}
\end{align}
To proceed, we simplify the expression $\text{pu}_{R}\bef(r\rightarrow...)$:
\begin{align}
 & \text{pu}_{R}\bef\big(r\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\bef r\big)=(m\rightarrow m\triangleright\text{pu}_{R})\bef\big(r\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\triangleright r\big)\nonumber \\
{\color{greenunder}\text{compute composition}:}\quad & =m\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\triangleright\left(m\triangleright\text{pu}_{R}\right)\quad.\label{eq:swap-laws-derivation1}
\end{align}
We now have to use the definition of $\text{pu}_{R}$, which is $\text{pu}_{R}=x\rightarrow y\rightarrow x$,
or in the pipe notation, 
\begin{equation}
y\triangleright\left(x\triangleright\text{pu}_{R}\right)=x\quad.\label{eq:rigid-monad-pure-t-simplification-1}
\end{equation}
With this simplification at hand, we continue from Eq.~(\ref{eq:swap-laws-derivation1})
to
\begin{align*}
 & m\rightarrow\gunderline{q\triangleright\text{pu}_{M}^{\downarrow H}\triangleright\left(m\triangleright\text{pu}_{R}\right)}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:rigid-monad-pure-t-simplification-1})}:}\quad & =m\rightarrow m=\text{id}\quad.
\end{align*}
Therefore, Eq.~(\ref{eq:swap-laws-derivation1a}) becomes
\[
m\rightarrow q\rightarrow m\triangleright\gunderline{\big(\text{pu}_{R}\bef\big(r\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\bef r\big)\big)^{\uparrow M}}=(m\rightarrow q\rightarrow\gunderline{m\triangleright\text{id}})=(m\rightarrow q\rightarrow m)=\text{pu}_{R}\quad.
\]
This proves the inner identity law.

\paragraph{The outer identity law}

is $\text{pu}_{M}\bef\text{sw}=\text{pu}_{M}^{\uparrow R}$. To verify
this law, write:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{pu}_{M}^{\uparrow R}:}\quad & \text{pu}_{M}\bef\gunderline{\text{sw}}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:rigid-monad-short-formula-for-swap})}:}\quad & =\big(m\rightarrow\gunderline{m\triangleright\text{pu}_{M}}\big)\bef\big(m\rightarrow q\rightarrow\gunderline m\triangleright\big(r\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\bef r\big)^{\uparrow M}\big)\\
{\color{greenunder}\text{compute composition}:}\quad & =m\rightarrow q\rightarrow m\triangleright\gunderline{\text{pu}_{M}\bef\big(r\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\bef r\big)^{\uparrow M}}\\
{\color{greenunder}\text{naturality law of }\text{pu}_{M}:}\quad & =m\rightarrow q\rightarrow m\triangleright\big(r\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\bef r\big)\bef\text{pu}_{M}\\
{\color{greenunder}\triangleright\text{-notation}:}\quad & =m\rightarrow q\rightarrow\gunderline{m\triangleright\big(r\rightarrow}q\triangleright\text{pu}_{M}^{\downarrow H}\bef\gunderline r\bef\text{pu}_{M}\big)\\
{\color{greenunder}\text{apply function to }m:}\quad & =m\rightarrow\gunderline{q\rightarrow q}\triangleright\text{pu}_{M}^{\downarrow H}\bef m\bef\text{pu}_{M}\\
{\color{greenunder}\text{unexpand function}:}\quad & =m\rightarrow\text{pu}_{M}^{\downarrow H}\bef m\bef\text{pu}_{M}\\
{\color{greenunder}\text{definition of }{}^{\uparrow R}:}\quad & =\text{pu}_{M}^{\uparrow R}\quad.
\end{align*}


\paragraph{The inner interchange law}

is written as
\begin{equation}
\text{ftn}_{R}^{\uparrow M}\bef\text{sw}=\text{sw}\bef\text{sw}^{\uparrow R}\bef\text{ftn}_{R}\quad.\label{eq:swap-law-3-formulation-R-M}
\end{equation}
We will apply both sides of the law to arbitrary $m:M^{R^{R^{A}}}$
and $q:H^{M^{A}}$, then rewrite both sides to the same expression. 

Below, we will need a simplified formula for $\text{ftn}_{R}$ derived
from Eq.~(\ref{eq:rigid-monad-flm-R-def}):
\begin{align}
\text{ftn}_{R} & =\text{flm}_{R}(\text{id})\nonumber \\
{\color{greenunder}\text{use Eq.~(\ref{eq:rigid-monad-flm-R-def})}:}\quad & =t\rightarrow q\rightarrow q\triangleright(t\triangleright(x\rightarrow x(q))^{\uparrow R})\nonumber \\
{\color{greenunder}\text{definition of }^{\uparrow R}:}\quad & =t\rightarrow q\rightarrow q\triangleright\big(t\triangleright\gunderline{\big(r\rightarrow}(x\rightarrow x(q))^{\downarrow H}\bef r\bef(x\rightarrow x(q))\big)\big)\nonumber \\
{\color{greenunder}\text{apply to argument}:}\quad & =t\rightarrow q\rightarrow q\triangleright\big((x\rightarrow x(q))^{\downarrow H}\bef t\bef(x\gunderline{\rightarrow x(q)})\big)\nonumber \\
{\color{greenunder}\text{use }\triangleright\text{-notation}:}\quad & =t\rightarrow q\rightarrow\gunderline{q\triangleright\big(q\triangleright(}x\rightarrow q\triangleright x)^{\downarrow H}\bef t\big)\quad.\label{eq:ftn-R-simplified}
\end{align}
We first apply the left-hand side of the law~(\ref{eq:swap-law-3-formulation-R-M})
to $m$ and $q$:
\begin{align*}
 & q\triangleright\big(m\triangleright\text{ftn}_{R}^{\uparrow M}\gunderline{\bef}\text{sw}\big)=q\triangleright\big(m\triangleright\text{ftn}_{R}^{\uparrow M}\triangleright\gunderline{\text{sw}}\big)\\
{\color{greenunder}\text{use Eq.~(\ref{eq:rigid-monad-choice-swap-short})}:}\quad & =m\triangleright\gunderline{\text{ftn}_{R}^{\uparrow M}\bef(r\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\bef r)^{\uparrow M}}\\
{\color{greenunder}\text{composition law of }M:}\quad & =m\triangleright\big(\text{ftn}_{R}\bef(r\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\bef r)\big)^{\uparrow M}\quad.
\end{align*}
We now need to simplify the sub-expression under $(...)^{\uparrow M}$:
\begin{align*}
 & \text{ftn}_{R}\gunderline{\bef(r}\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\triangleright r)\\
{\color{greenunder}\text{compute composition}:}\quad & =r\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\triangleright\gunderline{\text{ftn}_{R}(r)}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:ftn-R-simplified})}:}\quad & =r\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\triangleright\big(q\triangleright\gunderline{\text{pu}_{M}^{\downarrow H}\triangleright(x\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\triangleright x)^{\downarrow H}}\bef r\big)\\
{\color{greenunder}\text{composition law of }H:}\quad & =r\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\bef\big(q\triangleright(x\rightarrow q\triangleright\gunderline{\text{pu}_{M}^{\downarrow H}\bef x\bef\text{pu}_{M}})^{\downarrow H}\bef r\big)\\
{\color{greenunder}\text{definition of }^{\uparrow R}:}\quad & =r\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\bef\big(q\triangleright(x\rightarrow q\triangleright\text{pu}_{M}^{\uparrow R}(x))^{\downarrow H}\bef r\big)\quad.
\end{align*}
The left-hand side of the law~(\ref{eq:swap-law-3-formulation-R-M})
then becomes
\[
m\triangleright\big(r\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\bef\big(q\triangleright(x\rightarrow q\triangleright\text{pu}_{M}^{\uparrow R}(x))^{\downarrow H}\bef r\big)\big)^{\uparrow M}\quad.
\]
Now apply the right-hand side of the law~(\ref{eq:swap-law-3-formulation-R-M})
to $m$ and $q$:
\begin{align}
 & q\triangleright\big(m\triangleright\text{sw}\bef\gunderline{\text{sw}^{\uparrow R}}\bef\text{ftn}_{R}\big)\nonumber \\
{\color{greenunder}\text{definition of }^{\uparrow R}:}\quad & =q\triangleright\big(\gunderline{m\triangleright\text{sw}\triangleright(x}\rightarrow\text{sw}^{\downarrow H}\bef x\bef\text{sw})\triangleright\text{ftn}_{R}\big)\nonumber \\
{\color{greenunder}\text{apply to arguments}:}\quad & =q\triangleright\big(\gunderline{\text{ftn}_{R}(}\text{sw}^{\downarrow H}\bef\text{sw}(m)\bef\text{sw})\big)\nonumber \\
{\color{greenunder}\text{use Eq.~(\ref{eq:ftn-R-simplified})}:}\quad & =q\triangleright\big(q\triangleright\gunderline{(x\rightarrow q\triangleright x)^{\downarrow H}\bef\text{sw}^{\downarrow H}}\bef\text{sw}(m)\bef\text{sw}\big)\nonumber \\
{\color{greenunder}\text{composition under }^{\downarrow H}:}\quad & =q\triangleright\big(q\triangleright\big(\gunderline{\text{sw}\bef(x\rightarrow q\triangleright x)}\big)^{\downarrow H}\bef\text{sw}(m)\bef\text{sw}\big)\quad.\label{eq:swap-laws-derivation2}
\end{align}
To proceed, we simplify the sub-expression $\text{sw}(m)\bef\text{sw}$
by computing the function compositions:
\begin{align*}
 & \text{sw}(m)\bef\text{sw}\\
 & =(q_{1}\rightarrow m\triangleright\big(r\rightarrow q_{1}\triangleright\text{pu}_{M}^{\downarrow H}\bef r\big)^{\uparrow M}\gunderline{)\bef(}y\rightarrow q_{2}\rightarrow y\triangleright\big(r\rightarrow q_{2}\triangleright\text{pu}_{M}^{\downarrow H}\bef r\big)^{\uparrow M})\\
 & =q_{1}\rightarrow q_{2}\rightarrow(m\triangleright\big(r\rightarrow q_{1}\triangleright\text{pu}_{M}^{\downarrow H}\bef r\gunderline{\big)^{\uparrow M})\triangleright\big(}r\rightarrow q_{2}\triangleright\text{pu}_{M}^{\downarrow H}\bef r\gunderline{\big)^{\uparrow M}}\\
 & =q_{1}\rightarrow q_{2}\rightarrow m\triangleright\big(\big(r\rightarrow q_{1}\triangleright\text{pu}_{M}^{\downarrow H}\bef r\gunderline{\big)\bef\big(}r\rightarrow q_{2}\triangleright\text{pu}_{M}^{\downarrow H}\bef r\gunderline{\big)\big)^{\uparrow M}}\quad.
\end{align*}
Using this formula, we can write, for any $z$ of a suitable type,
\begin{align}
q\triangleright(z\triangleright\text{sw}(m)\bef\text{sw}) & =m\triangleright\big(\big(r\rightarrow z\triangleright\text{pu}_{M}^{\downarrow H}\bef r\gunderline{\big)\bef\big(r\rightarrow}q\triangleright\text{pu}_{M}^{\downarrow H}\bef r\big)\big)^{\uparrow M}\nonumber \\
{\color{greenunder}\text{compute composition}:}\quad & =m\triangleright\big(r\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\bef(z\triangleright\text{pu}_{M}^{\downarrow H}\bef r)\big)^{\uparrow M}\quad.\label{eq:swap-law-3-derivation-1}
\end{align}
Now we can substitute this into Eq.~(\ref{eq:swap-laws-derivation2}):
\begin{align*}
 & q\triangleright\big(q\triangleright\big(\text{sw}\bef(x\rightarrow q\triangleright x)\big)^{\downarrow H}\triangleright\gunderline{\text{sw}(m)\bef\text{sw}}\big)\\
{\color{greenunder}\text{use Eq.~(\ref{eq:swap-law-3-derivation-1})}:}\quad & =m\triangleright\big(r\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\bef(q\triangleright\gunderline{\big(\text{sw}\bef(x\rightarrow q\triangleright x)\big)^{\downarrow H}\triangleright\text{pu}_{M}^{\downarrow H}}\bef r)\big)^{\uparrow M}\\
{\color{greenunder}\text{composition under }^{\downarrow H}:}\quad & =m\triangleright\big(r\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\bef(q\triangleright\big(\gunderline{\text{pu}_{M}\bef\text{sw}}\bef(x\rightarrow q\triangleright x)\big)^{\downarrow H}\bef r)\big)^{\uparrow M}\\
{\color{greenunder}\text{outer identity law of }\text{sw}:}\quad & =m\triangleright\big(r\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\bef(q\triangleright\big(\gunderline{\text{pu}_{M}^{\uparrow R}\bef(x\rightarrow q\triangleright x)}\big)^{\downarrow H}\bef r)\big)^{\uparrow M}\\
{\color{greenunder}\text{compute composition}:}\quad & =m\triangleright\big(r\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\bef(q\triangleright\big(x\rightarrow q\triangleright\text{pu}_{M}^{\uparrow R}(x)\big)^{\downarrow H}\bef r)\big)^{\uparrow M}\quad.
\end{align*}
We arrived at the same expression as the left-hand side of the law.

\paragraph{The outer interchange law}

is written as
\begin{equation}
\text{ftn}_{M}\bef\text{sw}=\text{sw}^{\uparrow M}\bef\text{sw}\bef\text{ftn}_{M}^{\uparrow R}\quad.\label{eq:swap-law-4-formulation-R-M}
\end{equation}
We will apply both sides of the law to arbitrary $m^{:M^{M^{R^{A}}}}$
and $q^{:H^{M^{A}}}$, and transform both sides to the same expression.
We begin with the more complicated right-hand side and use the pipe
notation:
\begin{align}
 & q\triangleright\big(m\triangleright\text{sw}^{\uparrow M}\gunderline{\bef}\text{sw}\gunderline{\bef}\text{ftn}_{M}^{\uparrow R}\big)=q\triangleright\big((m\triangleright\text{sw}^{\uparrow M}\triangleright\text{sw})\triangleright\gunderline{\text{ftn}_{M}^{\uparrow R}}\big)\nonumber \\
{\color{greenunder}\text{definition of }^{\uparrow R}:}\quad & =q\triangleright\big(\text{ftn}_{M}^{\downarrow H}\gunderline{\bef}(m\triangleright\text{sw}^{\uparrow M}\triangleright\text{sw})\gunderline{\bef}\text{ftn}_{M}\big)\nonumber \\
{\color{greenunder}\triangleright\text{-notation}:}\quad & =\big(\gunderline{q\triangleright\text{ftn}_{M}^{\downarrow H}}\triangleright(\gunderline{m\triangleright\text{sw}^{\uparrow M}}\triangleright\gunderline{\text{sw}})\big)\triangleright\text{ftn}_{M}\nonumber \\
{\color{greenunder}\text{use Eq.~(\ref{eq:rigid-monad-choice-swap-short})}:}\quad & =\big(m\triangleright\gunderline{\text{sw}^{\uparrow M}}\triangleright\big(r\rightarrow q\triangleright\gunderline{\text{ftn}_{M}^{\downarrow H}\triangleright\text{pu}_{M}^{\downarrow H}}\bef r\gunderline{\big)^{\uparrow M}}\big)\triangleright\text{ftn}_{M}\nonumber \\
{\color{greenunder}\text{composition under }^{\downarrow H}\text{ and }^{\uparrow M}:}\quad & =m\triangleright\big(\text{sw}\bef\big(r\rightarrow q\triangleright(\gunderline{\text{pu}_{M}\bef\text{ftn}_{M}})^{\downarrow H}\bef r\big)\big)^{\uparrow M}\bef\text{ftn}_{M}\nonumber \\
{\color{greenunder}\text{left identity law of }M:}\quad & =m\triangleright\big(\text{sw}\bef(r\rightarrow q\triangleright r)\big)^{\uparrow M}\bef\text{ftn}_{M}\quad.\label{eq:rigid-monad-1-swap-law-4-derivation-5}
\end{align}
Let us simplify the sub-expression $\text{sw}\bef(r\rightarrow q\triangleright r)$
separately:
\begin{align*}
 & \gunderline{\text{sw}}\bef\big(r\rightarrow q\triangleright r\big)=(x\rightarrow x\triangleright\text{sw}\gunderline{)\bef(}r\rightarrow q\triangleright r)=x\rightarrow\gunderline{q\triangleright(x\triangleright\text{sw})}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:rigid-monad-choice-swap-short})}:}\quad & =\gunderline{x\rightarrow x\triangleright\big(}r\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\bef r\big)^{\uparrow M}=\big(r\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\bef r\big)^{\uparrow M}\quad.
\end{align*}
Substituting this expression into Eq.~(\ref{eq:rigid-monad-1-swap-law-4-derivation-5}),
we get
\begin{align*}
 & m\triangleright\big(\gunderline{\text{sw}\bef(r\rightarrow q\triangleright r)}\big)^{\uparrow M}\bef\text{ftn}_{M}=m\triangleright\big(r\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\bef r\gunderline{\big)^{\uparrow M\uparrow M}\bef\text{ftn}_{M}}\\
{\color{greenunder}\text{naturality law of }\text{ftn}_{M}:}\quad & =m\triangleright\text{ftn}_{M}\bef\big(r\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\bef r\big)^{\uparrow M}\quad.
\end{align*}

Now write the left-hand side of the law:
\begin{align*}
 & q\triangleright\big(m\triangleright\text{ftn}_{M}\gunderline{\bef}\text{sw}\big)=q\triangleright\big(m\triangleright\text{ftn}_{M}\triangleright\gunderline{\text{sw}}\big)\\
{\color{greenunder}\text{use Eq.~(\ref{eq:rigid-monad-choice-swap-short})}:}\quad & =m\triangleright\text{ftn}_{M}\triangleright\big(r\rightarrow q\triangleright\text{pu}_{M}^{\downarrow H}\bef r\big)^{\uparrow M}\quad.
\end{align*}
The two sides of the law are now equal.

\paragraph{The monadic naturality laws}

are written as
\[
\text{sw}_{R,\text{Id}}=\text{id}\quad,\quad\quad\text{sw}_{R,M}\bef\phi^{\uparrow R}=\phi\bef\text{sw}_{R,N}\quad,\quad\quad\text{sw}_{R,M}\bef\theta=\theta^{\uparrow M}\quad,
\]
where $\phi:M\leadsto N$ and $\theta:R\leadsto\text{Id}$ are arbitrary
monad morphisms. 

To verify the first law, set $M=\text{Id}$ in Eq.~(\ref{eq:rigid-monad-choice-swap-short})
and get
\begin{align*}
 & q\triangleright(m\triangleright\text{sw}_{R,\text{Id}})\\
{\color{greenunder}\text{use Eq.~(\ref{eq:rigid-monad-choice-swap-short})}:}\quad & =m\triangleright\big(r\rightarrow q\triangleright\gunderline{\text{pu}_{M}^{\downarrow H}}\bef r\gunderline{\big)^{\uparrow M}}\\
{\color{greenunder}\text{use }M=\text{Id}\text{ and }\text{pu}_{M}=\text{id}:}\quad & =\gunderline{m\triangleright(r\rightarrow}\,q\triangleright r)\\
{\color{greenunder}\text{apply to argument }m:}\quad & =q\triangleright\gunderline m=q\triangleright(m\triangleright\text{id})\quad.
\end{align*}
So, $\text{sw}_{R,\text{Id}}=\text{id}$ when applied to arbitrary
argument values $m$ and $q$.

To verify the second law, apply both sides to arbitrary $m$ and $q$.
The left-hand side:
\begin{align*}
 & q\triangleright\big(m\triangleright\text{sw}_{R,M}\gunderline{\bef}\phi^{\uparrow R}\big)=q\triangleright\big(m\triangleright\text{sw}_{R,M}\triangleright\gunderline{\phi^{\uparrow R}}\big)\\
{\color{greenunder}\text{definition of }^{\uparrow R}:}\quad & =q\triangleright\big(\phi^{\downarrow H}\bef(m\triangleright\text{sw}_{R,M})\bef\phi\big)\\
{\color{greenunder}\triangleright\text{-notation}:}\quad & =\gunderline{(q\triangleright\phi^{\downarrow H})}\triangleright(m\triangleright\gunderline{\text{sw}_{R,M}})\triangleright\phi\\
{\color{greenunder}\text{use Eq.~(\ref{eq:rigid-monad-choice-swap-short})}:}\quad & =m\triangleright\big(r\rightarrow q\triangleright\gunderline{\phi^{\downarrow H}\triangleright\text{pu}_{M}^{\downarrow H}}\bef r\big)^{\uparrow M}\triangleright\phi\\
{\color{greenunder}\text{composition law of }H:}\quad & =m\triangleright\big(r\rightarrow q\triangleright(\gunderline{\text{pu}_{M}\bef\phi})^{\downarrow H}\bef r\big)^{\uparrow M}\bef\phi\\
{\color{greenunder}\text{identity law of }\phi:}\quad & =m\triangleright\big(r\rightarrow q\triangleright\text{pu}_{N}^{\downarrow H}\bef r\gunderline{\big)^{\uparrow M}\bef\phi}\\
{\color{greenunder}\text{naturality law of }\phi:}\quad & =m\triangleright\phi\bef\big(r\rightarrow q\triangleright\text{pu}_{N}^{\downarrow H}\bef r\big)^{\uparrow N}\quad.
\end{align*}
The right-hand side, when applied to $m$ and $q$, gives the same
expression:
\begin{align*}
 & q\triangleright(m\triangleright\phi\bef\text{sw}_{R,N})=q\triangleright(m\triangleright\phi\triangleright\gunderline{\text{sw}_{R,N})}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:rigid-monad-choice-swap-short})}:}\quad & =m\triangleright\phi\triangleright\big(r\rightarrow q\triangleright\text{pu}_{N}^{\downarrow H}\bef r\big)^{\uparrow N}\quad.
\end{align*}

To argue that the third law holds,\footnote{The present proof needs an additional assumption about $\theta$,
which will be indicated below.} apply the left-hand side to $m$ and $q$:
\begin{align}
 & q\triangleright(m\triangleright\text{sw}_{R,M}\bef\theta)=q\triangleright(m\triangleright\text{sw}_{R,M}\triangleright\theta)\nonumber \\
 & =q\triangleright\big((q_{1}\rightarrow m\triangleright\big(r\rightarrow q_{1}\triangleright\text{pu}_{M}^{\downarrow H}\bef r\big)^{\uparrow M})\triangleright\theta\big)\quad.\label{eq:rigid-monad-1-derivation7}
\end{align}
This expression cannot be simplified any further; and neither can
the right-hand side, $q\triangleright(m\triangleright\theta^{\uparrow M})$.
We need more detailed information about the function $\theta$. The
type of $\theta$ is
\[
\theta:\forall A.\,(H^{A}\rightarrow A)\rightarrow A\quad.
\]
To implement a function of this type, we need to write code that takes
an argument of type $H^{A}\rightarrow A$ and returns a value of type
$A$. Since the type $A$ is arbitrary, the code of $\theta$ cannot
store a fixed value of type $A$ to use as the return value. It appears
that the only possibility of implementing a function $\theta$ is
by substituting a value of type $H^{A}$ into the given argument of
type $H^{A}\rightarrow A$. So,\footnote{We did not prove that the type $\forall A.\,(H^{A}\rightarrow A)\rightarrow A$
is \emph{equivalent} to $\forall A.\,H^{A}$. Later steps in the proof
assume that $\theta$ has the form shown in Eq.~(\ref{eq:rigid-monad-base-runner-1}).
Up to that assumption, the proof is rigorous.} we need to produce a value of type $H^{A}$ for an arbitrary type
$A$, that is, a value of type $\forall A.\,H^{A}$. Using the contravariant
Yoneda identity, we can simplify this type expression to the type
$H^{\bbnum 1}$:
\begin{align*}
 & \forall A.\,H^{A}\cong\forall A.\,\gunderline{\bbnum 1}\rightarrow H^{A}\\
{\color{greenunder}\text{use identity }(A\rightarrow\bbnum 1)\cong\bbnum 1:}\quad & \cong\forall A.\,(A\rightarrow\bbnum 1)\rightarrow H^{A}\\
{\color{greenunder}\text{contravariant Yoneda identity}:}\quad & \cong H^{\bbnum 1}\quad.
\end{align*}
So, we can construct a $\theta$ if we take a value $h_{1}$ of type
$H^{\bbnum 1}$ and compute $h:H^{A}$ as
\[
h^{:H^{A}}=h_{1}^{:H^{1}}\triangleright(a^{:A}\rightarrow1)^{\downarrow H}\quad.
\]
For any given value $h_{1}:H^{\bbnum 1}$, we can implement a runner
$\theta$ as
\begin{equation}
\big(r^{:H^{A}\rightarrow A}\big)\triangleright\theta\triangleq h_{1}\triangleright(\_\rightarrow1)^{\downarrow H}\triangleright r\quad.\label{eq:rigid-monad-base-runner-1}
\end{equation}
Let us check whether this $\theta$ is a monad morphism $R\leadsto\text{Id}$.
We need to verify the laws:
\[
\text{pu}_{R}\bef\theta=\text{id}\quad,\quad\quad\text{ftn}_{R}\bef\theta=\theta^{\uparrow R}\bef\theta=\theta\bef\theta\quad.
\]
The identity law, after applying both sides to an arbitrary $x^{:A}$,
has the form
\begin{align*}
{\color{greenunder}\text{expect to equal }x:}\quad & x\triangleright\text{pu}_{R}\bef\theta=(x\triangleright\text{pu}_{R}\gunderline{)\triangleright\theta}\\
{\color{greenunder}\text{definition of }r\triangleright\theta:}\quad & =h_{1}\triangleright(\_\rightarrow1)^{\downarrow H}\triangleright(\gunderline{x\triangleright\text{pu}_{R}})\\
{\color{greenunder}\text{definition of }x\triangleright\text{pu}_{R}:}\quad & =\big(h_{1}\triangleright(\_\rightarrow1)^{\downarrow H}\gunderline{\big)\triangleright(\_\rightarrow}x)\\
{\color{greenunder}\text{compute composition}:}\quad & =x\quad.
\end{align*}
This verifies the identity law. 

The composition law, applied to an arbitrary $r:R^{R^{A}}$, expands
to
\begin{align*}
 & r\triangleright\text{ftn}_{R}\bef\theta=\gunderline{r\triangleright\text{ftn}_{R}}\triangleright\theta\\
{\color{greenunder}\text{definition of }\text{ftn}_{R}:}\quad & =\gunderline{r\triangleright\big(t\rightarrow}q\rightarrow q\triangleright\big(q\triangleright(x\rightarrow q\triangleright x)^{\downarrow H}\bef t\big)\big)\triangleright\theta\\
{\color{greenunder}\text{apply to }r:}\quad & =\big(q\rightarrow q\triangleright\big(q\triangleright(x\rightarrow q\triangleright x)^{\downarrow H}\bef r\big)\gunderline{\big)\triangleright\theta}\\
{\color{greenunder}\text{definition~(\ref{eq:rigid-monad-base-runner-1}) of }\theta:}\quad & =h_{1}\triangleright(\_\rightarrow1)^{\downarrow H}\triangleright\gunderline{\big(q\rightarrow}q\triangleright\big(q\triangleright(x\rightarrow q\triangleright x)^{\downarrow H}\bef r\big)\big)\\
{\color{greenunder}\text{apply to }h_{1}\triangleright(\_\rightarrow1)^{\downarrow H}:}\quad & =h_{1}\triangleright(\_\rightarrow1)^{\downarrow H}\triangleright\big(h_{1}\triangleright\gunderline{(\_\rightarrow1)^{\downarrow H}\bef(x\rightarrow...)^{\downarrow H}}\bef r\big)\\
{\color{greenunder}\text{composition under }^{\downarrow H}:}\quad & =\gunderline{h_{1}\triangleright(\_\rightarrow1)^{\downarrow H}}\triangleright\big(\gunderline{h_{1}\triangleright(\_\rightarrow1)^{\downarrow H}}\triangleright r\big)\\
{\color{greenunder}\text{definition~(\ref{eq:rigid-monad-base-runner-1}) of }\theta:}\quad & =r\triangleright\theta\triangleright\theta=r\triangleright\theta\bef\theta\quad.
\end{align*}
This verifies the composition law; so $\theta$ is indeed a monad
morphism.

Using the code of $\theta$ defined in Eq.~(\ref{eq:rigid-monad-base-runner-1}),
we can now verify the monadic naturality law of $\text{sw}_{R,M}$
(with respect to the runners $\theta$ of that form). The left-hand
side of the law is given by Eq.~(\ref{eq:rigid-monad-1-derivation7}):
\begin{align*}
 & q\triangleright\big((q_{1}\rightarrow m\triangleright\big(r\rightarrow q_{1}\triangleright\text{pu}_{M}^{\downarrow H}\bef r\big)^{\uparrow M}\gunderline{)\triangleright\theta}\big)\\
{\color{greenunder}\text{definition of }\theta:}\quad & =q\triangleright\big(h_{1}\triangleright(\_\rightarrow1)^{\downarrow H}\gunderline{\triangleright(q_{1}\rightarrow}m\triangleright\big(r\rightarrow q_{1}\triangleright\text{pu}_{M}^{\downarrow H}\bef r\big)^{\uparrow M})\big)\\
{\color{greenunder}\text{apply to argument}:}\quad & =q\triangleright\big(m\triangleright\big(r\rightarrow h_{1}\triangleright\gunderline{(\_\rightarrow1)^{\downarrow H}\triangleright\text{pu}_{M}^{\downarrow H}}\bef r\big)^{\uparrow M}\big)\\
{\color{greenunder}\text{composition under }^{\downarrow H}:}\quad & =q\triangleright\big(m\triangleright\big(r\rightarrow h_{1}\triangleright(\gunderline{\text{pu}_{M}\bef(\_\rightarrow1)})^{\downarrow H}\bef r\big)^{\uparrow M}\big)\\
{\color{greenunder}\text{compute composition}:}\quad & =q\triangleright\big(m\triangleright\big(r\rightarrow h_{1}\triangleright(\gunderline{\_\rightarrow1})^{\downarrow H}\triangleright r\big)^{\uparrow M}\big)\quad.
\end{align*}
The right-hand side is
\begin{align*}
 & q\triangleright(m\triangleright\gunderline{\theta}^{\uparrow M})\\
{\color{greenunder}\text{expand function}:}\quad & =q\triangleright\big(m\triangleright\big(r\rightarrow\gunderline{r\triangleright\theta}\big)^{\uparrow M}\big)\\
{\color{greenunder}\text{definition~(\ref{eq:rigid-monad-base-runner-1}) of }\theta:}\quad & =q\triangleright\big(m\triangleright\big(r\rightarrow h_{1}\triangleright(\_\rightarrow1)^{\downarrow H}\triangleright r\big)^{\uparrow M}\big)\quad.
\end{align*}
This expression is now the same as the left-hand side.

This concludes the proof of the laws for the \textsf{``}choice\textsf{''} monad\textsf{'}s
transformer.

\section{Transformers for some monad constructions}

\subsection{Transformer for products of monads. Proofs}

The product of any two monads is again a monad (Statement~\ref{subsec:Statement-monad-semimonad-product}).
If the two monads have known transformers, the product of the two
transformers is the transformer for the product monad. 

For instance, the product of \lstinline!Either! and \lstinline!Reader!
monads, $L^{A}\triangleq(E+A)\times(R\rightarrow A)$, has the transformer
\[
T_{L}^{M,A}\triangleq M^{E+A}\times(R\rightarrow M^{A})\quad.
\]
Note that this monad transformer is neither composed-outside nor composed-inside.

\subsubsection{Statement \label{subsec:Statement-product-of-monad-transformers}\ref{subsec:Statement-product-of-monad-transformers}}

The product of two lawful monad transformers satisfies all transformer
laws.

\subparagraph{Proof}

Given two monads $G$ and $H$ whose transformers $T_{G}$ and $T_{H}$
are known, we need to show that a lawful transformer for the monad
$L^{\bullet}\triangleq G^{\bullet}\times H^{\bullet}$ is given by
\[
T_{L}^{M,A}\triangleq T_{G}^{M,A}\times T_{H}^{M,A}\quad.
\]
We will assume that all monad transformer laws already hold for $T_{G}$
and $T_{H}$.

\paragraph{Monad laws}

Since $T_{G}^{M}$ and $T_{H}^{M}$ are (by assumption) lawful monads,
$T_{L}^{M}$ is a lawful monad by the product construction (Statement~\ref{subsec:Statement-monad-semimonad-product}).

\paragraph{Identity laws}

With $M=\text{Id}$, we have $T_{L}^{\text{Id}}=T_{G}^{\text{Id}}\times T_{H}^{\text{Id}}$.
The equivalence $T_{G}^{\text{Id}}\times T_{H}^{\text{Id}}\cong G\times H$
is found via the pair product of the monad morphisms $T_{G}^{\text{Id}}\cong G$
and $T_{H}^{\text{Id}}\cong H$. The pair product of two monad morphisms
is again a monad morphism (Statement~\ref{subsec:Statement-pair-product-of-monadic-morphisms}).

\paragraph{Lifting laws}

We define the foreign lift function (\lstinline!flift!) via the pair
product:
\[
\text{flift}_{L}^{:M\leadsto T_{G}^{M}\times T_{H}^{M}}\triangleq\Delta\bef(\text{flift}_{G}\boxtimes\text{flift}_{H})\quad.
\]
To show that $\text{flift}_{L}$ is a monad morphism, we use the properties
that $\Delta:M\leadsto M\times M$ is a monad morphism (Statement~\ref{subsec:Statement-M-to-M-times-M-is-monadic-morphism}),
that the pair product preserves monad morphisms (Statement~\ref{subsec:Statement-pair-product-of-monadic-morphisms}),
and that function composition also preserves monad morphisms (Statement~\ref{subsec:Statement-monadic-morphism-composition}).

\paragraph{Runner laws}

We need to define the foreign runner (\lstinline!frun!):
\[
\text{frun}_{L}(\phi^{:M\leadsto N}):T_{G}^{M,A}\times T_{H}^{M,A}\leadsto T_{G}^{N,A}\times T_{H}^{N,A}\quad,\quad\quad\text{frun}_{L}(\phi)\triangleq\text{frun}_{G}(\phi)\boxtimes\text{frun}_{H}(\phi)\quad.
\]
The function returned by $\text{frun}_{L}(\phi)$ is a monad morphism
by Statement~\ref{subsec:Statement-pair-product-of-monadic-morphisms}.

The functor laws hold due to the properties of the pair product:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{id}:}\quad & \text{frun}_{L}(\text{id})=\text{frun}_{G}(\text{id})\boxtimes\text{frun}_{H}(\text{id})=\text{id}\boxtimes\text{id}=\text{id}\quad,\\
{\color{greenunder}\text{expect to equal }\text{frun}_{L}(\phi\bef\chi):}\quad & \text{frun}_{L}(\phi)\bef\text{frun}_{L}(\chi)=\big(\gunderline{\text{frun}_{G}(\phi)\bef\text{frun}_{G}(\chi)}\big)\boxtimes\big(\gunderline{\text{frun}_{H}(\phi)\bef\text{frun}_{H}(\chi)}\big)\\
{\color{greenunder}\text{functor laws of }\text{frun}_{G},\,\text{frun}_{H}:}\quad & \quad=\text{frun}_{G}(\phi\bef\chi)\boxtimes\text{frun}_{H}(\phi\bef\chi)=\text{frun}_{L}(\phi\bef\chi)\quad.
\end{align*}


\paragraph{Base runner laws}

We may define a base runner in two different ways, by dropping either
the first or the second part of the product. Both base runners are
lawful. Consider the first one:
\[
\text{brun}_{L}:T_{G}^{M}\times T_{H}^{M}\leadsto M\quad,\quad\quad\text{brun}_{L}\triangleq\pi_{1}\bef\text{brun}_{G}\quad.
\]
It is a monad morphism because it is a composition of a projection
(Statement~\ref{subsec:Statement-projection-is-monadic-morphism})
and a monad morphism $\text{brun}_{G}$. Function composition preserves
monad morphisms (Statement~\ref{subsec:Statement-monadic-morphism-composition}).

The non-degeneracy law holds because it holds for $\text{brun}_{G}$:
\[
\text{flift}_{L}\bef\text{brun}_{L}=\Delta\bef\gunderline{(\text{flift}_{G}\boxtimes\text{flift}_{H})\bef\pi_{1}}\bef\text{brun}_{G}=\gunderline{\Delta\bef\pi_{1}}\bef\gunderline{\text{flift}_{G}\bef\text{brun}_{G}}=\text{id}\quad.
\]
Analogous proofs work for the other definition, $\text{brun}_{L}\triangleq\pi_{2}\bef\text{brun}_{H}$.

A deficiency of these base runners is that the effects of one of the
monads ($G$ or $H$) are being ignored, which loses information.
If we would like to run the effects of both monads $G$ and $H$,
we can instead implement a base runner into the monad $M\times M$.
This corresponds to running the monad $G\times H$ into the \textsf{``}double-valued\textsf{''}
monad $D^{A}\triangleq A\times A$, since $T_{D}^{M}=M\times M$.
Define the base runner as:
\[
\text{brun}_{L}:T_{G}^{M}\times T_{H}^{M}\leadsto M\times M\quad,\quad\quad\text{brun}_{L}\triangleq\text{brun}_{G}\boxtimes\text{brun}_{H}\quad.
\]
This is a monad morphism due to Statement~\ref{subsec:Statement-pair-product-of-monadic-morphisms}.
The non-degeneracy law has the form
\[
\text{flift}_{L}\bef\text{brun}_{L}=\Delta^{:M\leadsto M\times M}\quad,
\]
since the target monad is now $M\times M$. To verify the non-degeneracy
law:
\begin{align*}
 & \text{flift}_{L}\bef\text{brun}_{L}=\Delta\bef(\text{flift}_{G}\boxtimes\text{flift}_{H})\bef(\text{brun}_{G}\boxtimes\text{brun}_{H})\\
 & =\Delta\bef(\gunderline{\text{flift}_{G}\bef\text{brun}_{G}})\boxtimes(\gunderline{\text{flift}_{H}\bef\text{brun}_{H}})=\Delta\bef(\text{id}\boxtimes\text{id})=\Delta\quad.
\end{align*}


\paragraph{Monadic naturality laws}

To verify the monadic naturality law of $\text{flift}_{L}$:
\begin{align*}
 & \text{flift}_{L}\bef\text{frun}_{L}(\phi)=\Delta\bef(\text{flift}_{G}\boxtimes\text{flift}_{H})\bef(\text{frun}_{G}(\phi)\boxtimes\text{frun}_{H}(\phi))\\
 & =\Delta\bef(\gunderline{\text{flift}_{G}\bef\text{frun}_{G}}(\phi))\boxtimes(\gunderline{\text{flift}_{H}\bef\text{frun}_{H}(\phi)})=\Delta\bef(\gunderline{\phi}\bef\text{flift}_{G})\boxtimes(\gunderline{\phi}\bef\text{flift}_{H})\\
 & =\gunderline{\Delta\bef(\phi\boxtimes\phi)}\bef(\text{flift}_{G}\boxtimes\text{flift}_{H})=\phi\bef\gunderline{\Delta\bef(\text{flift}_{G}\boxtimes\text{flift}_{H})}=\phi\bef\text{flift}_{L}\quad.
\end{align*}

To verify the monadic naturality law of an information-losing definition
of $\text{brun}_{L}$:
\begin{align*}
 & \text{frun}_{L}(\phi)\bef\text{brun}_{L}=\gunderline{(\text{frun}_{G}(\phi)\boxtimes\text{frun}_{H}(\phi))\bef\pi_{1}}\bef\text{brun}_{G}=\pi_{1}\bef\text{frun}_{G}(\phi)\bef\text{brun}_{G}\quad,\\
 & \text{brun}_{L}\bef\phi=\pi_{1}\bef\gunderline{\text{brun}_{G}\bef\phi}=\pi_{1}\bef\text{frun}_{G}(\phi)\bef\text{brun}_{G}\quad.
\end{align*}
The runner $\text{brun}_{L}:T_{L}^{M}\leadsto M\times M$ also obeys
a monadic naturality law involving $\phi\boxtimes\phi$ instead of
$\phi$:
\begin{align*}
 & \text{frun}_{L}(\phi)\bef\text{brun}_{L}=(\text{frun}_{G}(\phi)\boxtimes\text{frun}_{H}(\phi))\bef(\text{brun}_{G}\boxtimes\text{brun}_{H})\\
 & =(\gunderline{\text{frun}_{G}(\phi)\bef\text{brun}_{G}})\boxtimes(\gunderline{\text{frun}_{H}(\phi)\bef\text{brun}_{H}})=(\text{brun}_{G}\bef\phi)\boxtimes(\text{brun}_{H}\bef\phi)\\
 & =(\text{brun}_{G}\boxtimes\text{brun}_{H})\bef(\phi\boxtimes\phi)\quad.
\end{align*}


\subsection{Transformer for free pointed monads. Proofs}

For an arbitrary monad $K$, a \textbf{free pointed monad} \index{free pointed monad}\index{monads!free pointed}\textbf{on}
$K$ is defined as the monad $L^{A}\triangleq A+K^{A}$ (see Statement~\ref{subsec:Statement-co-product-with-identity-monad}).
An example of a free pointed monad is the \lstinline!Eval! monad
(Section~\ref{subsec:The-eager-lazy-evaluation-monad}) having the
type $A+(\bbnum 1\rightarrow A)$, which is of the form $A+K^{A}$
with $K^{A}\triangleq\bbnum 1\rightarrow A$ being a \lstinline!Reader!
monad. 

Assuming that a given monad $K$ has a lawful transformer, we will
now show that the free pointed monad on $K$ also has a monad transformer
satisfying all laws.

\subsubsection{Statement \label{subsec:Statement-free-pointed-monad-transformer}\ref{subsec:Statement-free-pointed-monad-transformer}}

The monad $L$\textsf{'}s transformer is defined by the type formula
\[
T_{L}^{M,A}\triangleq M^{A+T_{K}^{M,A}}\quad,
\]
where $T_{K}$ is the monad $K$\textsf{'}s transformer, which is assumed to
be known. 

\subparagraph{Proof}

We will define the necessary methods for $T_{L}$ when we need them
in the course of the proof.

To verify the monad transformer laws for $T_{L}$, we begin by observing
that $A+T_{K}^{M,A}$ is a free pointed monad on $T_{K}^{M}$. Let
us denote for brevity 
\[
N^{A}\triangleq T_{K}^{M,A}\quad,\quad\quad P^{A}\triangleq A+T_{K}^{M,A}=A+N^{A}\quad,\quad\quad T_{L}^{M,A}\triangleq M^{P^{A}}=\left(M\circ P\right)^{A}\quad.
\]
We know from Statement~\ref{subsec:Statement-co-product-with-identity-monad}
that $P$\textsf{'}s monad methods are defined by
\[
\text{pu}_{P}\triangleq a^{:A}\rightarrow a+\bbnum 0^{:N^{A}}\quad,\quad\text{ftn}_{P}\triangleq\,\begin{array}{|c||cc|}
 & A & N^{A}\\
\hline A & \text{id} & \bbnum 0\\
N^{A} & \bbnum 0 & \text{id}\\
N^{P^{A}} & \bbnum 0 & \gamma^{\uparrow N}\bef\text{ftn}_{N}
\end{array}\quad,\quad\text{where}\quad\gamma^{:P^{A}\rightarrow N^{A}}\triangleq\,\begin{array}{|c||c|}
 & N^{A}\\
\hline A & \text{pu}_{N}\\
N^{A} & \text{id}
\end{array}\quad.
\]
The transformer $T_{L}$ is a composition of the foreign monad $M$
outside $P$. To show that $T_{L}$ is a monad, we may use Statement~\ref{sec:Statement-swap-laws-to-monad-transformer-first-law},
which requires a suitable \lstinline!swap! function (denoted by \textsf{``}$\text{sw}$\textsf{''}):
\begin{equation}
\text{sw}:P^{M^{A}}\rightarrow M^{P^{A}}\quad,\quad\quad\text{sw}\triangleq\,\begin{array}{|c||c|}
 & M^{A+N^{A}}\\
\hline M^{A} & \text{pu}_{P}^{\uparrow M}\\
N^{M^{A}} & (t\rightarrow\bbnum 0^{:A}+\text{merge}\,(t))\bef\text{pu}_{M}
\end{array}\quad.\label{eq:def-of-swap-for-free-pointed-monad-transformer}
\end{equation}
Here, \lstinline!merge! is a helper function that combines all effects
contained within $N^{M^{A}}$ into one $N$-effect represented by
a value of type $N^{A}$:
\[
\text{merge}:N^{M^{A}}\rightarrow N^{A}\quad,\quad\quad\text{merge}\triangleq\text{flift}_{K}^{\uparrow N}\bef\text{ftn}_{N}\quad.
\]
We will now verify all monad transformer laws for $T_{L}.$

\paragraph{Monad laws}

The monad methods of $T_{L}$ are defined as in Statement~\ref{sec:Statement-swap-laws-to-monad-transformer-first-law}:
\[
\text{pu}_{T}\triangleq\text{pu}_{P}\bef\text{pu}_{M}=(a^{:A}\rightarrow a+\bbnum 0^{:N^{A}})\bef\text{pu}_{M}\quad,\quad\quad\text{ftn}_{T}\triangleq\text{sw}^{\uparrow M}\bef\text{ftn}_{M}\bef\text{ftn}_{P}^{\uparrow M}\quad.
\]
The composition $T_{L}^{M}\triangleq M\circ P$ is a monad as long
as the \lstinline!swap! function obeys the naturality law and the
four laws given in Statement~\ref{sec:Statement-swap-laws-to-monad-transformer-first-law},
if we replace $L$ and $M$ by $M$ and $P$. Let us verify those
laws.

The \lstinline!swap! function is a natural transformation because
it is a combination of various natural transformations such as $\text{pu}_{M}$
and \lstinline!merge!.

The outer identity law is $\text{pu}_{M}^{\uparrow P}\bef\text{sw}=\text{pu}_{M}$.
We rewrite the left-hand side, expecting to obtain $\text{pu}_{M}$:
\begin{align*}
 & \text{pu}_{M}^{\uparrow P}\bef\text{sw}=\,\begin{array}{|c||cc|}
 & M^{A} & N^{M^{A}}\\
\hline A & \text{pu}_{M} & \bbnum 0\\
N^{A} & \bbnum 0 & \text{pu}_{M}^{\uparrow N}
\end{array}\,\bef\,\begin{array}{|c||c|}
 & M^{A+N^{A}}\\
\hline M^{A} & (a\rightarrow a+\bbnum 0^{:N^{A}})^{\uparrow M}\\
N^{M^{A}} & (t\rightarrow\bbnum 0^{:A}+\text{merge}\,(t))\bef\text{pu}_{M}
\end{array}\\
 & =\,\begin{array}{|c||c|}
 & M^{A+N^{A}}\\
\hline A & \text{pu}_{M}\bef(a\rightarrow a+\bbnum 0^{:N^{A}})^{\uparrow M}\\
N^{A} & \text{pu}_{M}^{\uparrow N}\bef(t\rightarrow\bbnum 0^{:A}+\text{merge}\,(t))\bef\text{pu}_{M}
\end{array}\,=\,\begin{array}{|c||c|}
 & M^{A+N^{A}}\\
\hline A & (a\rightarrow a+\bbnum 0^{:N^{A}})\bef\text{pu}_{M}\\
N^{A} & (n\rightarrow\bbnum 0^{:A}+\text{merge}\,(n\triangleright\text{pu}_{M}^{\uparrow N}))\bef\text{pu}_{M}
\end{array}\\
 & =\,\,\begin{array}{|c||c|}
 & A+N^{A}\\
\hline A & a\rightarrow a+\bbnum 0^{:N^{A}}\\
N^{A} & n\rightarrow\bbnum 0^{:A}+n\triangleright\text{pu}_{M}^{\uparrow N}\bef\text{merge}
\end{array}\,\bef\text{pu}_{M}=\,\begin{array}{|c||cc|}
 & A & N^{A}\\
\hline A & \text{id} & \bbnum 0\\
N^{A} & \bbnum 0 & \text{pu}_{M}^{\uparrow N}\bef\text{merge}
\end{array}\,\bef\text{pu}_{M}\quad.
\end{align*}
It remains to show that the matrix element $\text{pu}_{M}^{\uparrow N}\bef\text{merge}$
is equal to the identity function:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{id}:}\quad & \text{pu}_{M}^{\uparrow N}\bef\text{merge}=\gunderline{\text{pu}_{M}^{\uparrow N}\bef\text{flift}_{K}^{\uparrow N}}\bef\text{ftn}_{N}\\
{\color{greenunder}\text{monad morphism law of }\text{flift}_{K}:}\quad & =\text{pu}_{N}^{\uparrow N}\bef\text{ftn}_{N}=\text{id}\quad.
\end{align*}

The inner identity law is $\text{pu}_{P}\bef\text{sw}=\text{pu}_{P}^{\uparrow M}$.
Begin with the left-hand side:
\begin{align*}
 & \text{pu}_{P}\bef\text{sw}=(m^{:M^{A}}\rightarrow m+\bbnum 0^{:N^{M^{A}}})\bef\text{sw}\\
 & =\,\begin{array}{|c||cc|}
 & M^{A} & N^{M^{A}}\\
\hline M^{A} & \text{id} & \bbnum 0
\end{array}\,\bef\,\begin{array}{|c||c|}
 & M^{A+N^{A}}\\
\hline M^{A} & \text{pu}_{P}^{\uparrow M}\\
N^{M^{A}} & (n\rightarrow\bbnum 0^{:A}+\text{merge}\,(n))\bef\text{pu}_{M}
\end{array}\,=\text{pu}_{P}^{\uparrow M}\quad.
\end{align*}

The outer interchange law is
\[
\text{ftn}_{M}^{\uparrow P}\bef\text{sw}=\text{sw}\bef\text{sw}^{\uparrow M}\bef\text{ftn}_{M}\quad.
\]
Begin with the right-hand side since it is more complicated, and use
the identity law we just proved:
\begin{align*}
 & \text{sw}\bef\text{sw}^{\uparrow M}\bef\text{ftn}_{M}=\,\begin{array}{|c||c|}
 & M^{A+N^{A}}\\
\hline M^{M^{A}} & \gunderline{\text{pu}_{P}^{\uparrow M}\bef\text{sw}^{\uparrow M}}\bef\text{ftn}_{M}\\
N^{M^{M^{A}}} & (n\rightarrow\bbnum 0+\text{merge}\,(t))\bef\gunderline{\text{pu}_{M}\bef\text{sw}^{\uparrow M}}\bef\text{ftn}_{M}
\end{array}\\
 & =\,\begin{array}{||c|}
\gunderline{\text{pu}_{P}^{\uparrow M\uparrow M}\bef\text{ftn}_{M}}\\
(t\rightarrow\bbnum 0+\text{merge}\,(t))\bef\text{sw}\bef\gunderline{\text{pu}_{M}\bef\text{ftn}_{M}}
\end{array}\,=\,\begin{array}{||c|}
\text{ftn}_{M}\bef\text{pu}_{P}^{\uparrow M}\\
(t\rightarrow\bbnum 0+\text{merge}\,(t))\bef\text{sw}
\end{array}\quad.
\end{align*}
The left-hand side of the law is written as:
\begin{align*}
 & \text{ftn}_{M}^{\uparrow P}\bef\text{sw}=\,\begin{array}{|c||cc|}
 & M^{A} & N^{M^{A}}\\
\hline M^{M^{A}} & \text{ftn}_{M} & \bbnum 0\\
N^{M^{M^{A}}} & \bbnum 0 & \text{ftn}_{M}^{\uparrow N}
\end{array}\,\bef\,\begin{array}{|c||c|}
 & M^{A+N^{A}}\\
\hline M^{A} & \text{pu}_{P}^{\uparrow M}\\
N^{M^{A}} & (t\rightarrow\bbnum 0+\text{merge}\,(t))\bef\text{pu}_{M}
\end{array}\\
 & =\,\begin{array}{|c||c|}
 & M^{A+N^{A}}\\
\hline M^{M^{A}} & \text{ftn}_{M}\bef\text{pu}_{P}^{\uparrow M}\\
N^{M^{M^{A}}} & \text{ftn}_{M}^{\uparrow N}\bef(t\rightarrow\bbnum 0+\text{merge}\,(t))\bef\text{pu}_{M}
\end{array}\quad.
\end{align*}
The first rows of the matrices for the two sides of the law are now
equal (to $\text{ftn}_{M}\bef\text{pu}_{P}^{\uparrow M}$). It remains
to show that  the second rows of the matrices are also equal:
\begin{align*}
 & (t\rightarrow\bbnum 0+\text{merge}\,(t))\bef\text{sw}\overset{?}{=}\text{ftn}_{M}^{\uparrow N}\bef(t\rightarrow\bbnum 0+\text{merge}\,(t))\bef\text{pu}_{M}\quad,\\
{\color{greenunder}\text{apply both sides to }t:}\quad & (\bbnum 0+t\triangleright\text{merge})\,\gunderline{\triangleright\,\text{sw}}\overset{?}{=}\big(\bbnum 0+t\triangleright\text{ftn}_{M}^{\uparrow N}\triangleright\text{merge}\big)\triangleright\text{pu}_{M}\quad,\\
{\color{greenunder}\text{apply }\text{sw}:}\quad & (\bbnum 0+t\triangleright\text{merge}\triangleright\text{merge})\triangleright\text{pu}_{M}\overset{?}{=}\big(\bbnum 0+t\triangleright\text{ftn}_{M}^{\uparrow N}\triangleright\text{merge}\big)\triangleright\text{pu}_{M}\quad.
\end{align*}
We will prove the last equality if we show that the function \lstinline!merge!
has the following property:
\[
\text{merge}\bef\text{merge}=\text{ftn}_{M}^{\uparrow N}\bef\text{merge}\quad,\quad\text{or}:\quad\text{flift}_{K}^{\uparrow N}\bef\text{ftn}_{N}\bef\text{flift}_{K}^{\uparrow N}\bef\text{ftn}_{N}=\text{ftn}_{M}^{\uparrow N}\bef\text{flift}_{K}^{\uparrow N}\bef\text{ftn}_{N}\quad.
\]

\begin{wrapfigure}{l}{0.26\columnwidth}%
\vspace{-3\baselineskip}

\[
\xymatrix{\xyScaleY{1.8pc}\xyScaleX{3.5pc}N^{M^{M^{A}}}\ar[r]\sp(0.55){\text{merge}^{M^{A}}}\ar[d]\sb(0.45){\text{ftn}_{M}^{\uparrow N}} & N^{M^{A}}\ar[d]\sb(0.45){\text{merge}^{A}}\\
N^{M^{A}}\ar[r]\sp(0.55){\text{merge}^{A}} & N^{A}
}
\]
\vspace{-1.2\baselineskip}
\end{wrapfigure}%

\noindent We know nothing about the transformer $T_{K}$\textsf{'}s \lstinline!flift!
function except for its laws. The law connecting \lstinline!flift!
and \lstinline!flatten! is the lifting law:
\begin{equation}
\text{flift}_{K}\bef\text{flift}_{K}^{\uparrow N}\bef\text{ftn}_{N}=\text{ftn}_{M}\bef\text{flift}_{K}\quad.\label{eq:free-pointed-transformer-use-lifting-derivation1}
\end{equation}
To make use of that law, we use other laws to transform the expression
$\text{merge}\bef\text{merge}$, so that the two \lstinline!flift!
functions are composed together and are followed by $\text{ftn}_{N}$:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{ftn}_{M}^{\uparrow N}\bef\text{merge}:}\quad & \text{merge}\bef\text{merge}=\text{flift}_{K}^{\uparrow N}\bef\gunderline{\text{ftn}_{N}\bef\text{flift}_{K}^{\uparrow N}}\bef\text{ftn}_{N}\\
{\color{greenunder}\text{naturality of }\text{ftn}_{N}:}\quad & =\text{flift}_{K}^{\uparrow N}\bef\text{flift}_{K}^{\uparrow N\uparrow N}\bef\gunderline{\text{ftn}_{N}\bef\text{ftn}_{N}}\\
{\color{greenunder}\text{associativity law of }\text{ftn}_{N}:}\quad & =\gunderline{\text{flift}_{K}^{\uparrow N}\bef\text{flift}_{K}^{\uparrow N\uparrow N}\bef\text{ftn}_{N}^{\uparrow N}}\bef\text{ftn}_{N}=(\gunderline{\text{flift}_{K}\bef\text{flift}_{K}^{\uparrow N}\bef\text{ftn}_{N}})^{\uparrow N}\bef\text{ftn}_{N}\\
{\color{greenunder}\text{lifting law~(\ref{eq:free-pointed-transformer-use-lifting-derivation1})}:}\quad & =\gunderline{(\text{ftn}_{M}\bef\text{flift}_{K})^{\uparrow N}}\bef\text{ftn}_{N}=\text{ftn}_{M}^{\uparrow N}\bef\gunderline{\text{flift}_{K}^{\uparrow N}\bef\text{ftn}_{N}}=\text{ftn}_{M}^{\uparrow N}\bef\text{merge}\quad.
\end{align*}
This completes the proof of the outer interchange law of \lstinline!swap!.

The inner interchange law is
\[
\text{ftn}_{P}\bef\text{sw}=\text{sw}^{\uparrow P}\bef\text{sw}\bef\text{ftn}_{P}^{\uparrow M}\quad.
\]
The left-hand side of that law is rewritten as:
\begin{align*}
 & \text{ftn}_{P}\bef\text{sw}=\,\begin{array}{|c||cc|}
 & M^{A} & N^{M^{A}}\\
\hline M^{A} & \text{id} & \bbnum 0\\
N^{M^{A}} & \bbnum 0 & \text{id}\\
N^{P^{M^{A}}} & \bbnum 0 & \gamma^{\uparrow N}\bef\text{ftn}_{N}
\end{array}\,\bef\,\begin{array}{|c||c|}
 & M^{P^{A}}\\
\hline M^{A} & \text{pu}_{P}^{\uparrow M}\\
N^{M^{A}} & (t\rightarrow\bbnum 0+\text{merge}\,(t))\bef\text{pu}_{M}
\end{array}\\
 & =\,\begin{array}{|c||c|}
 & M^{P^{A}}\\
\hline M^{A} & \text{pu}_{P}^{\uparrow M}\\
N^{M^{A}} & (t\rightarrow\bbnum 0+\text{merge}\,(t))\bef\text{pu}_{M}\\
N^{P^{M^{A}}} & \gamma^{\uparrow N}\bef\text{ftn}_{N}\bef(t\rightarrow\bbnum 0+\text{merge}\,(t))\bef\text{pu}_{M}
\end{array}\quad.
\end{align*}
The right-hand side is rewritten using the identity law of $\text{ftn}_{P}$
and the naturality law of $\text{pu}_{P}$:
\begin{align*}
 & \text{sw}^{\uparrow P}\bef\text{sw}\bef\text{ftn}_{P}^{\uparrow M}\\
 & =\,\begin{array}{|c||cc|}
 & M^{P^{A}} & N^{M^{P^{A}}}\\
\hline M^{A} & \text{pu}_{P}^{\uparrow M} & \bbnum 0\\
N^{M^{A}} & (t\rightarrow\bbnum 0+\text{merge}\,(t))\bef\text{pu}_{M} & \bbnum 0\\
N^{P^{M^{A}}} & \bbnum 0 & \text{sw}^{\uparrow N}
\end{array}\,\bef\,\begin{array}{|c||c|}
 & M^{P^{A}}\\
\hline M^{P^{A}} & \gunderline{\text{pu}_{P}^{\uparrow M}\bef\text{ftn}_{P}^{\uparrow M}}\\
N^{M^{P^{A}}} & (t\rightarrow\bbnum 0+\text{merge}\,(t))\bef\gunderline{\text{pu}_{M}\bef\text{ftn}_{P}^{\uparrow M}}
\end{array}\\
 & =\,\,\begin{array}{|c||c|}
 & M^{P^{A}}\\
\hline M^{A} & \text{pu}_{P}^{\uparrow M}\\
N^{M^{A}} & (t\rightarrow\bbnum 0+\text{merge}\,(t))\bef\text{pu}_{M}\\
N^{P^{M^{A}}} & \text{sw}^{\uparrow N}\bef(t\rightarrow\bbnum 0+\text{merge}\,(t))\bef\text{ftn}_{P}\bef\text{pu}_{M}
\end{array}\quad.
\end{align*}
The difference between the two sides is only in the third rows of
the matrices:
\[
\gamma^{\uparrow N}\bef\text{ftn}_{N}\bef(t\rightarrow\bbnum 0+\text{merge}\,(t))\bef\text{pu}_{M}\overset{?}{=}\text{sw}^{\uparrow N}\bef(t\rightarrow\bbnum 0+\text{merge}\,(t))\bef\text{ftn}_{P}\bef\text{pu}_{M}\quad.
\]
We can omit the composition with $\text{pu}_{M}$ if we can prove
a stronger condition:
\begin{equation}
\gamma^{\uparrow N}\bef\text{ftn}_{N}\bef(t\rightarrow\bbnum 0+\text{merge}\,(t))\overset{?}{=}\text{sw}^{\uparrow N}\bef(t\rightarrow\bbnum 0+\text{merge}\,(t))\bef\text{ftn}_{P}\quad.\label{free-pointed-transformer-derivation0}
\end{equation}
Apply both sides of Eq.~(\ref{free-pointed-transformer-derivation0})
to an arbitrary $n:N^{P^{M^{A}}}$. The left-hand side becomes:
\begin{align*}
 & n\triangleright\gamma^{\uparrow N}\bef\text{ftn}_{N}\bef(t\rightarrow\bbnum 0+\text{merge}\,(t))=\bbnum 0+n\triangleright\gamma^{\uparrow N}\triangleright\text{ftn}_{N}\triangleright\text{merge}\quad.
\end{align*}
The right-hand side of Eq.~(\ref{free-pointed-transformer-derivation0})
applied to $n$ is
\begin{align*}
 & n\triangleright\text{sw}^{\uparrow N}\bef(t\rightarrow\bbnum 0+\text{merge}\,(t))\bef\text{ftn}_{P}=(\bbnum 0+n\triangleright\text{sw}^{\uparrow N}\triangleright\text{merge})\triangleright\text{ftn}_{P}\\
 & =(\bbnum 0+n\triangleright\text{sw}^{\uparrow N}\bef\text{merge})\triangleright\,\begin{array}{|c||cc|}
 & A & N^{A}\\
\hline A & \text{id} & \bbnum 0\\
N^{A} & \bbnum 0 & \text{id}\\
N^{P^{A}} & \bbnum 0 & \gamma^{\uparrow N}\bef\text{ftn}_{N}
\end{array}\,=\bbnum 0+n\triangleright\text{sw}^{\uparrow N}\bef\text{merge}\bef\gamma^{\uparrow N}\bef\text{ftn}_{N}\quad.
\end{align*}
The remaining difference is between two functions of type $N^{P^{M^{A}}}\rightarrow N^{A}$:
\begin{equation}
\gamma^{\uparrow N}\bef\text{ftn}_{N}\bef\text{merge}\overset{?}{=}\text{sw}^{\uparrow N}\bef\text{merge}\bef\gamma^{\uparrow N}\bef\text{ftn}_{N}\quad.\label{eq:free-pointed-transformer-derivation1}
\end{equation}
The left-hand side of Eq.~(\ref{eq:free-pointed-transformer-derivation1})
can be rewritten as
\begin{align*}
 & \gamma^{\uparrow N}\bef\text{ftn}_{N}\bef\text{merge}=\gamma^{\uparrow N}\bef\gunderline{\text{ftn}_{N}\bef\text{flift}_{K}^{\uparrow N}}\bef\text{ftn}_{N}\\
{\color{greenunder}\text{naturality of }\text{ftn}_{N}:}\quad & =\gamma^{\uparrow N}\bef\text{flift}_{K}^{\uparrow N\uparrow N}\bef\gunderline{\text{ftn}_{N}\bef\text{ftn}_{N}}\\
{\color{greenunder}\text{associativity law of }\text{ftn}_{N}:}\quad & =\gamma^{\uparrow N}\bef\text{flift}_{K}^{\uparrow N\uparrow N}\bef\text{ftn}_{N}^{\uparrow N}\bef\text{ftn}_{N}=\big(\gamma\bef\text{flift}_{K}^{\uparrow N}\bef\text{ftn}_{N}\big)^{\uparrow N}\bef\text{ftn}_{N}\quad.
\end{align*}
The right-hand side of Eq.~(\ref{eq:free-pointed-transformer-derivation1})
is
\begin{align*}
 & \text{sw}^{\uparrow N}\bef\text{merge}\bef\gamma^{\uparrow N}\bef\text{ftn}_{N}\\
{\color{greenunder}\text{naturality of }\text{merge}:}\quad & =\text{sw}^{\uparrow N}\bef\gamma^{\uparrow M\uparrow N}\bef\text{merge}\bef\text{ftn}_{N}=\text{sw}^{\uparrow N}\bef\gamma^{\uparrow M\uparrow N}\bef\text{flift}_{K}^{\uparrow N}\bef\gunderline{\text{ftn}_{N}\bef\text{ftn}_{N}}\\
{\color{greenunder}\text{associativity law of }\text{ftn}_{N}:}\quad & =\big(\text{sw}\bef\gamma^{\uparrow M}\bef\text{flift}_{K}\bef\text{ftn}_{N}\big)^{\uparrow N}\bef\text{ftn}_{N}\quad.
\end{align*}
The remaining difference is now between two functions of type $P^{M^{A}}\rightarrow N^{A}$:
\begin{equation}
\gamma\bef\text{flift}_{K}^{\uparrow N}\bef\text{ftn}_{N}\overset{?}{=}\text{sw}\bef\gamma^{\uparrow M}\bef\text{flift}_{K}\bef\text{ftn}_{N}\quad.\label{eq:free-pointed-transformer-derivation2}
\end{equation}
The left-hand side of Eq.~(\ref{eq:free-pointed-transformer-derivation2})
is 
\begin{align*}
 & \gamma\bef\text{flift}_{K}^{\uparrow N}\bef\text{ftn}_{N}=\,\begin{array}{|c||c|}
 & N^{M^{A}}\\
\hline M^{A} & \text{pu}_{N}\\
N^{M^{A}} & \text{id}
\end{array}\,\bef\text{flift}_{K}^{\uparrow N}\bef\text{ftn}_{N}=\,\begin{array}{|c||c|}
 & N^{A}\\
\hline M^{A} & \gunderline{\text{pu}_{N}\bef\text{flift}_{K}^{\uparrow N}}\bef\text{ftn}_{N}\\
N^{M^{A}} & \text{id}\bef\text{flift}_{K}^{\uparrow N}\bef\text{ftn}_{N}
\end{array}\\
 & =\,\begin{array}{|c||c|}
 & N^{A}\\
\hline M^{A} & \text{flift}_{K}\bef\gunderline{\text{pu}_{N}\bef\text{ftn}_{N}}\\
N^{M^{A}} & \text{id}\bef\gunderline{\text{flift}_{K}^{\uparrow N}\bef\text{ftn}_{N}}
\end{array}\,=\,\begin{array}{|c||c|}
 & N^{A}\\
\hline M^{A} & \text{flift}_{K}\\
N^{M^{A}} & \text{merge}
\end{array}\quad.
\end{align*}
To proceed with the right-hand side of Eq.~(\ref{eq:free-pointed-transformer-derivation2}),
we compute some intermediate expressions:
\begin{align*}
 & \text{sw}\bef\gamma^{\uparrow M}=\,\begin{array}{|c||c|}
 & M^{N^{A}}\\
\hline M^{A} & \text{pu}_{P}^{\uparrow M}\bef\gamma^{\uparrow M}\\
N^{M^{A}} & (t\rightarrow\bbnum 0+\text{merge}\,(t))\bef\text{pu}_{M}\bef\gamma^{\uparrow M}
\end{array}\quad,\\
 & \text{pu}_{P}\bef\gamma=(a^{:A}\rightarrow a+\bbnum 0)\bef\,\begin{array}{|c||c|}
 & N^{A}\\
\hline A & \text{pu}_{N}\\
N^{A} & \text{id}
\end{array}\,=a^{:A}\rightarrow\text{pu}_{N}(a)=\text{pu}_{N}\quad,\\
 & (t\rightarrow\bbnum 0+\text{merge}\,(t))\bef\text{pu}_{M}\bef\gamma^{\uparrow M}=(t\rightarrow\bbnum 0+\text{merge}\,(t))\bef\gamma\bef\text{pu}_{M}\\
 & \quad=(t\rightarrow\bbnum 0+\text{merge}\,(t))\bef\,\begin{array}{|c||c|}
 & N^{A}\\
\hline A & \text{pu}_{N}\\
N^{A} & \text{id}
\end{array}\,\bef\text{pu}_{M}=t\rightarrow\text{merge}\,(t)\triangleright\text{pu}_{M}=\text{merge}\bef\text{pu}_{M}\quad.
\end{align*}
Now we can reduce the right-hand side of Eq.~(\ref{eq:free-pointed-transformer-derivation2})
to
\begin{align*}
 & \text{sw}\bef\gamma^{\uparrow M}\bef\text{flift}_{K}\bef\text{ftn}_{N}=\,\begin{array}{|c||c|}
 & N^{A}\\
\hline M^{A} & \gunderline{\text{pu}_{N}^{\uparrow M}\bef\text{flift}_{K}}\bef\text{ftn}_{N}\\
N^{M^{A}} & \text{merge}\bef\gunderline{\text{pu}_{M}\bef\text{flift}_{K}}\bef\text{ftn}_{N}
\end{array}\\
 & =\,\begin{array}{|c||c|}
 & N^{A}\\
\hline M^{A} & \text{flift}_{K}\bef\gunderline{\text{pu}_{N}^{\uparrow N}\bef\text{ftn}_{N}}\\
N^{M^{A}} & \text{merge}\bef\gunderline{\text{pu}_{N}\bef\text{ftn}_{N}}
\end{array}\,=\,\begin{array}{|c||c|}
 & N^{A}\\
\hline M^{A} & \text{flift}_{K}\\
N^{M^{A}} & \text{merge}
\end{array}\quad.
\end{align*}
This equals the left-hand side of Eq.~(\ref{eq:free-pointed-transformer-derivation2}).

\paragraph{Identity laws}

The identity laws hold: setting $M=\text{Id}$ in the type of $T_{L}^{M}$
gives the isomorphism
\[
T_{L}^{\text{Id},A}\triangleq\text{Id}^{A+T_{K}^{\text{Id},A}}\cong A+K^{A}\triangleq L^{A}\quad.
\]
The two directions of the isomorphism $A+T_{K}^{\text{Id},A}\cong A+K^{A}$
are monad morphisms due to Statement~\ref{subsec:Statement-composition-transformer-identity-law},
assuming that the identity law already holds for the transformer $T_{K}$.
We also need the property that the free pointed construction preserves
monad morphisms (Exercise~\ref{par:Exercise-mt-3}). Then the assumed
monad isomorphism $T_{K}^{\text{Id}}\cong K$ extends to a monad isomorphism
$A+T_{K}^{\text{Id},A}\cong A+K^{A}$.

\paragraph{Lifting laws}

The function \lstinline!flift! for $T_{L}$ is defined by
\[
\text{flift}_{L}:M^{A}\rightarrow M^{P^{A}}\quad,\quad\quad\text{flift}_{L}\triangleq\text{pu}_{P}^{\uparrow M}\quad.
\]
To show that \lstinline!flift! is a monad morphism, we refer to Statement~\ref{subsec:Statement-transformer-lifting-laws-from-swap},
where we need to use \lstinline!blift! instead of \lstinline!flift!
and consider $P$ as the base monad and $M$ as the foreign monad.

\paragraph{Implementation of runners}

We cannot use Statement~\ref{subsec:Statement-monad-transformer-runner-laws-from-swap}
to verify the runner laws for $T_{L}$, because the transformer $T_{L}^{M}=M\circ P$
is not compositional: the monad $P$ uses in its definition the monad
$M$ as $P^{A}\triangleq A+T_{K}^{M,A}$. Mapping the monad $M$ to
$M^{\prime}$ requires us also to map $P$ to $P^{\prime}\triangleq A+T_{K}^{M^{\prime},A}$.
So, the runners (\lstinline!frun! and \lstinline!brun!) must be
defined differently from those in Statement~\ref{subsec:Statement-monad-transformer-runner-laws-from-swap}:
\begin{align*}
 & \text{frun}_{L}^{M,M^{\prime}}\!:(M\leadsto M^{\prime})\rightarrow M^{P^{A}}\rightarrow M^{\prime P^{\prime A}}\!\quad,\quad\text{frun}_{L}^{M,M^{\prime}}\!(\phi^{:M\leadsto M^{\prime}})\triangleq\,\begin{array}{|c||cc|}
 & A & T_{K}^{M^{\prime},A}\\
\hline A & \text{id} & \bbnum 0\\
T_{K}^{M,A} & \bbnum 0 & \text{frun}_{K}^{M,M^{\prime}}\!(\phi)
\end{array}^{\uparrow M}\bef\phi\quad,
\end{align*}
\begin{align*}
 & \text{brun}_{L}:(L\leadsto\text{Id})\rightarrow M^{P^{A}}\rightarrow M^{A}\quad,\quad\text{brun}_{L}(\theta^{:L\leadsto\text{Id}})\triangleq\,\begin{array}{|c||c|}
 & M^{A}\\
\hline A & \text{pu}_{M}\\
T_{K}^{M,A} & \text{brun}_{K}((k\rightarrow\bbnum 0+k)\bef\theta)
\end{array}^{\uparrow M}\bef\text{ftn}_{M}\quad.
\end{align*}
The function $(k\rightarrow\bbnum 0+k)\bef\theta$ is a runner $K\leadsto\text{Id}$
as shown by Exercise~\ref{par:Exercise-mt-3-2-1}(d). If the transformer
$T_{K}^{M}$ does not have a general base runner, the definition of
$\text{brun}_{L}$ above will need to use any available base runner
$\text{brun}_{K}$ instead of $\text{brun}_{K}((k\rightarrow\bbnum 0+k)\bef\theta)$.

If the transformer $T_{K}$ has no base runner, we will be unable
to define a base runner for $T_{L}$.

\paragraph{Monadic naturality of \texttt{swap}}

The code of \lstinline!swap! is the same for any foreign monad $M$;
it means that \lstinline!swap! is natural in the monad parameter
$M$. However, since the monad $P$ depends on $M$, the monadic naturality
of $\text{sw}_{M,P}$ with respect to the monad $M$ is not simply
the monadic naturality of the function \lstinline!swap[M[_], P[_], A]!
with respect to the type parameter \lstinline!M[_]!. For any monad
morphism $\phi:M\leadsto M^{\prime}$, we need to use the corresponding
monad morphism between $P\leadsto P^{\prime}$ (see Exercise~\ref{par:Exercise-mt-3}),
which we will temporarily denote by $\psi$:
\[
\psi\triangleq\,\begin{array}{|c||cc|}
 & A & T_{K}^{M^{\prime},A}\\
\hline A & \text{id} & \bbnum 0\\
T_{K}^{M,A} & \bbnum 0 & \text{frun}_{K}^{M,M^{\prime}}\!(\phi)
\end{array}\quad.
\]
We now write the monadic naturality law relating $\text{sw}_{M,P}$
and $\text{sw}_{M^{\prime},P^{\prime}}$ as follows:

\begin{wrapfigure}{l}{0.38\columnwidth}%
\vspace{-2\baselineskip}

\[
\xymatrix{\xyScaleY{1.5pc}\xyScaleX{2.3pc}P^{M^{A}}\ar[d]\sb(0.45){\text{sw}_{M,P}}\ar[r]\sp(0.5){\phi^{\uparrow P}} & P^{M^{\prime A}}\ar[r]\sp(0.45){\psi} & P^{\prime M^{\prime A}}\ar[d]\sb(0.45){\,\text{sw}_{M^{\prime},P^{\prime}}}\\
M^{P^{A}}\ar[r]\sp(0.5){\psi^{\uparrow M}} & M^{P^{\prime A}}\ar[r]\sp(0.45){\phi} & M^{\prime P^{\prime A}}
}
\]
\vspace{0.4\baselineskip}
\end{wrapfigure}%

~\vspace{-0.4\baselineskip}
\begin{equation}
\text{sw}_{M,P}\bef\psi^{\uparrow M}\bef\phi=\phi^{\uparrow P}\bef\psi\bef\text{sw}_{M^{\prime},P^{\prime}}\quad.\label{eq:monadic-naturality-free-pointed-swap}
\end{equation}
To verify this law, substitute the definition of $\text{sw}_{M,P}$
into its two sides:
\begin{align*}
 & \text{sw}_{M,P}\bef\psi^{\uparrow M}\bef\phi=\,\begin{array}{|c||c|}
 & M^{\prime P^{\prime A}}\\
\hline M^{A} & \text{pu}_{P}^{\uparrow M}\bef\psi^{\uparrow M}\bef\phi\\
N^{M^{A}} & (t\rightarrow\bbnum 0+\text{merge}\,(t))\bef\text{pu}_{M}\bef\psi^{\uparrow M}\bef\phi
\end{array}\,=\,\begin{array}{||c|}
\text{pu}_{P}^{\uparrow M}\bef\psi^{\uparrow M}\bef\phi\\
(t\rightarrow\bbnum 0+\text{merge}\,(t))\bef\text{pu}_{M}\bef\psi^{\uparrow M}\bef\phi
\end{array}\\
 & \quad=\,\begin{array}{||c|}
\phi\bef(\text{pu}_{P}\bef\psi)^{\uparrow M^{\prime}}\\
(t\rightarrow\bbnum 0+\text{merge}\,(t))\bef\psi\bef\text{pu}_{M}\bef\phi
\end{array}\,=\,\begin{array}{||c|}
\phi\bef\text{pu}_{P^{\prime}}^{\uparrow M^{\prime}}\\
(t\rightarrow\bbnum 0+\text{merge}\,(t))\bef\psi\bef\text{pu}_{M^{\prime}}
\end{array}\quad,\\
 & \phi^{\uparrow P}\bef\psi\bef\text{sw}_{M^{\prime},P^{\prime}}=\,\begin{array}{|c||cc|}
 & M^{\prime A} & N^{M^{\prime A}}\\
\hline M^{A} & \phi & \bbnum 0\\
N^{M^{A}} & \bbnum 0 & \phi^{\uparrow N}
\end{array}\,\bef\,\begin{array}{|c||cc|}
 & M^{\prime A} & T_{K}^{M^{\prime},M^{\prime A}}\\
\hline M^{\prime A} & \text{id} & \bbnum 0\\
T_{K}^{M,M^{\prime A}} & \bbnum 0 & \text{frun}_{K}^{M,M^{\prime}}\!(\phi)
\end{array}\,\bef\text{sw}_{M^{\prime},P^{\prime}}\\
 & \quad=\,\begin{array}{|c||cc|}
 & M^{\prime A} & T_{K}^{M^{\prime},M^{\prime A}}\\
\hline M^{A} & \phi & \bbnum 0\\
T_{K}^{M,M^{A}} & \bbnum 0 & \phi^{\uparrow N}\bef\text{frun}_{K}^{M,M^{\prime}}\!(\phi)
\end{array}\,\bef\,\begin{array}{|c||c|}
 & M^{\prime P^{\prime A}}\\
\hline M^{\prime A} & \text{pu}_{P^{\prime}}^{\uparrow M^{\prime}}\\
T_{K}^{M^{\prime},M^{\prime A}} & (t\rightarrow\bbnum 0+\text{merge}\,(t))\bef\text{pu}_{M^{\prime}}
\end{array}\\
 & \quad=\,\,\begin{array}{|c||c|}
 & M^{\prime P^{\prime A}}\\
\hline M^{A} & \phi\bef\text{pu}_{P^{\prime}}^{\uparrow M^{\prime}}\\
T_{K}^{M,M^{A}} & \phi^{\uparrow N}\bef\text{frun}_{K}^{M,M^{\prime}}\!(\phi)\bef(t\rightarrow\bbnum 0+\text{merge}\,(t))\bef\text{pu}_{M^{\prime}}
\end{array}\quad.
\end{align*}
It remains to show the equality of two functions of type $T_{K}^{M,M^{A}}\rightarrow A+T_{K}^{M^{\prime},A}=N^{M^{A}}\rightarrow A+T_{K}^{M^{\prime},A}$:
\begin{align*}
 & \phi^{\uparrow N}\bef\text{frun}_{K}^{M,M^{\prime}}\!(\phi)\bef(t\rightarrow\bbnum 0+\text{merge}\,(t))\overset{?}{=}(t\rightarrow\bbnum 0+\text{merge}\,(t))\bef\psi\\
 & =(t\rightarrow\bbnum 0+\text{merge}\,(t))\bef\,\begin{array}{|c||cc|}
 & A & T_{K}^{M^{\prime},A}\\
\hline A & \text{id} & \bbnum 0\\
T_{K}^{M,A} & \bbnum 0 & \text{frun}_{K}^{M,M^{\prime}}\!(\phi)
\end{array}\,=t\rightarrow\bbnum 0+t\triangleright\text{merge}\triangleright\text{frun}_{K}^{M,M^{\prime}}\!(\phi)\quad.
\end{align*}
Since both functions produce results of type $\bbnum 0^{:A}+T_{K}^{M^{\prime},A}$,
we need to compare the following two functions of type $N^{M^{A}}\rightarrow N^{\prime A}$,
where we denote for brevity $N^{\prime A}\triangleq T_{K}^{M^{\prime},A}$:
\begin{align}
 & \phi^{\uparrow N}\bef\text{frun}_{K}^{M,M^{\prime}}\!(\phi)\bef\text{merge}\overset{?}{=}\text{merge}\bef\text{frun}_{K}^{M,M^{\prime}}(\phi)\quad,\nonumber \\
{\color{greenunder}\text{or equivalently}:}\quad & \phi^{\uparrow N}\bef\text{frun}_{K}^{M,M^{\prime}}\!(\phi)\bef\text{flift}_{K}^{\uparrow N^{\prime}}\bef\text{ftn}_{N^{\prime}}\overset{?}{=}\text{flift}_{K}^{\uparrow N}\bef\text{ftn}_{N}\bef\text{frun}_{K}^{M,M^{\prime}}(\phi)\quad.\label{eq:free-pointed-sw-monadic-naturality-derivation1}
\end{align}
Rewrite the left-hand side of Eq.~(\ref{eq:free-pointed-sw-monadic-naturality-derivation1})
so that $\text{frun}\left(\phi\right)$ is moved to the right in the
composition:
\begin{align*}
 & \phi^{\uparrow N}\bef\gunderline{\text{frun}_{K}^{M,M^{\prime}}\!(\phi)\bef\text{flift}_{K}^{\uparrow N^{\prime}}}\bef\text{ftn}_{N^{\prime}}=(\gunderline{\phi\bef\text{flift}_{K}})^{\uparrow N}\bef\text{frun}_{K}^{M,M^{\prime}}\!(\phi)\bef\text{ftn}_{N^{\prime}}\\
{\color{greenunder}\text{use law~(\ref{eq:monadic-naturality-law-of-flift})}:}\quad & =\text{flift}_{K}^{\uparrow N}\bef\gunderline{\big(\text{frun}_{K}^{M,M^{\prime}}\!(\phi)\big)^{\uparrow N}\bef\text{frun}_{K}^{M,M^{\prime}}\!(\phi)\bef\text{ftn}_{N^{\prime}}}\\
{\color{greenunder}\text{composition law of }\text{frun}_{K}:}\quad & =\text{flift}_{K}^{\uparrow N}\bef\text{ftn}_{N}\bef\text{frun}_{K}^{M,M^{\prime}}\!(\phi)\quad.
\end{align*}
This equals the right-hand side of Eq.~(\ref{eq:free-pointed-sw-monadic-naturality-derivation1}),
proving the monadic naturality law~(\ref{eq:monadic-naturality-free-pointed-swap}).

\paragraph{Runner laws}

To show that $\text{frun}_{L}^{M,M^{\prime}}(\phi)$ is a monad morphism,
first verify the identity law:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{pu}_{M^{\prime}\circ P^{\prime}}:}\quad & \text{pu}_{M\circ P}\bef\text{frun}_{L}^{M,M^{\prime}}\!(\phi)=\text{pu}_{P}\bef\gunderline{\text{pu}_{M}\bef\psi^{\uparrow M}}\bef\phi\\
{\color{greenunder}\text{naturality law of }\text{pu}_{M}:}\quad & =\gunderline{\text{pu}_{P}\bef\psi}\bef\gunderline{\text{pu}_{M}\bef\phi}\\
{\color{greenunder}\text{identity laws of }\phi\text{ and }\psi:}\quad & =\text{pu}_{P^{\prime}}\bef\text{pu}_{M^{\prime}}=\text{pu}_{M^{\prime}\circ P^{\prime}}\quad.
\end{align*}

To verify the composition law, express $\text{frun}_{L}^{M,M^{\prime}}=\psi^{\uparrow M}\bef\phi$
and recall that $f^{\uparrow(M\circ P)}=f^{\uparrow P\uparrow M}$:
\begin{align*}
{\color{greenunder}\text{left-hand side}:}\quad & (\psi^{\uparrow M}\bef\phi)^{\uparrow(M\circ P)}\bef\psi^{\uparrow M}\bef\phi\bef\text{ftn}_{M^{\prime}\circ P^{\prime}}\\
{\color{greenunder}\text{definition of }\text{ftn}_{M^{\prime}\circ P^{\prime}}:}\quad & \quad=(\psi^{\uparrow M}\bef\phi)^{\uparrow(M\circ P)}\bef\psi^{\uparrow M}\bef\phi\bef\text{sw}_{M^{\prime},P^{\prime}}^{\uparrow M^{\prime}}\bef\text{ftn}_{M^{\prime}}\bef\text{ftn}_{P^{\prime}}^{\uparrow M^{\prime}}\quad,\\
{\color{greenunder}\text{right-hand side}:}\quad & \text{ftn}_{M\circ P}\bef\psi^{\uparrow M}\bef\phi=\text{sw}_{M,P}^{\uparrow M}\bef\text{ftn}_{M}\bef\text{ftn}_{P}^{\uparrow M}\bef\psi^{\uparrow M}\bef\phi\quad.
\end{align*}
We need to use various laws to rewrite the left-hand side so that
the functions $\psi$ and $\phi$ are moved to the right in the function
composition:
\begin{align*}
{\color{greenunder}\text{left-hand side}:}\quad & (\psi^{\uparrow M}\bef\phi)^{\uparrow(M\circ P)}\bef\psi^{\uparrow M}\bef\phi\bef\text{ftn}_{M^{\prime}\circ P^{\prime}}\\
{\color{greenunder}\text{definition of }\text{ftn}_{M^{\prime}\circ P^{\prime}}:}\quad & =(\psi^{\uparrow M}\bef\phi)^{\uparrow(M\circ P)}\bef\psi^{\uparrow M}\bef\gunderline{\phi\bef\text{sw}_{M^{\prime},P^{\prime}}^{\uparrow M^{\prime}}}\bef\text{ftn}_{M^{\prime}}\bef\text{ftn}_{P^{\prime}}^{\uparrow M^{\prime}}\\
{\color{greenunder}\text{naturality law of }\phi:}\quad & =\gunderline{(\psi^{\uparrow M}\bef\phi)^{\uparrow P\uparrow M}\bef\psi^{\uparrow M}\bef\text{sw}_{M^{\prime},P^{\prime}}^{\uparrow M}}\bef\phi\bef\text{ftn}_{M^{\prime}}\bef\text{ftn}_{P^{\prime}}^{\uparrow M^{\prime}}\\
{\color{greenunder}\text{composition under }^{\uparrow M}:}\quad & =\big(\psi^{\uparrow M\uparrow P}\bef\gunderline{\phi^{\uparrow P}\bef\psi\bef\text{sw}_{M^{\prime},P^{\prime}}}\big)^{\uparrow M}\bef\phi\bef\text{ftn}_{M^{\prime}}\bef\text{ftn}_{P^{\prime}}^{\uparrow M^{\prime}}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:monadic-naturality-free-pointed-swap}) for }\text{sw}_{M^{\prime},P^{\prime}}:}\quad & =\big(\psi^{\uparrow M\uparrow P}\bef\text{sw}_{M,P}\bef\psi^{\uparrow M}\bef\gunderline{\phi\big)^{\uparrow M}\bef\phi\bef\text{ftn}_{M^{\prime}}}\bef\text{ftn}_{P^{\prime}}^{\uparrow M^{\prime}}\\
{\color{greenunder}\text{composition law of }\phi:}\quad & =\big(\gunderline{\psi^{\uparrow M\uparrow P}\bef\text{sw}_{M,P}}\bef\gunderline{\psi^{\uparrow M}\big)^{\uparrow M}\bef\text{ftn}_{M}}\bef\gunderline{\phi\bef\text{ftn}_{P^{\prime}}^{\uparrow M^{\prime}}}\\
{\color{greenunder}\text{naturality of }\text{sw}\text{, }\phi\text{, and }\text{ftn}_{M}:}\quad & =\big(\text{sw}_{M,P}\bef\gunderline{\psi^{\uparrow P\uparrow M}\big)^{\uparrow M}\bef\text{ftn}_{M}}\bef\psi^{\uparrow M}\bef\text{ftn}_{P^{\prime}}^{\uparrow M}\bef\phi\\
{\color{greenunder}\text{naturality law of }\text{ftn}_{M}:}\quad & =\text{sw}_{M,P}^{\uparrow P}\bef\text{ftn}_{M}\bef\big(\gunderline{\psi^{\uparrow P}\bef\psi\bef\text{ftn}_{P^{\prime}}}\big)^{\uparrow M}\bef\phi\\
{\color{greenunder}\text{composition law of }\psi:}\quad & =\text{sw}_{M,P}^{\uparrow P}\bef\text{ftn}_{M}\bef(\text{ftn}_{P}\bef\psi)^{\uparrow M}\bef\phi=\text{sw}_{M,P}^{\uparrow P}\bef\text{ftn}_{M}\bef\text{ftn}_{P}^{\uparrow M}\bef\psi^{\uparrow M}\bef\phi\quad.
\end{align*}
Both sides are now equal, which concludes the proof of the monad morphism
laws of $\text{frun}_{L}$.

\paragraph{Functor laws of \texttt{frun}}

To verify the functor laws of $\text{frun}_{L}$, we assume that the
functor laws already hold for $\text{frun}_{K}$. The identity law
of $\text{frun}_{L}$ is:
\[
\text{frun}_{L}^{M,M}(\text{id})=\,\begin{array}{|c||cc|}
 & A & T_{K}^{M,A}\\
\hline A & \text{id} & \bbnum 0\\
T_{K}^{M,A} & \bbnum 0 & \text{frun}_{K}^{M,M}(\text{id})
\end{array}^{\uparrow M}\bef\text{id}=\,\begin{array}{|c||cc|}
 & A & T_{K}^{M,A}\\
\hline A & \text{id} & \bbnum 0\\
T_{K}^{M,A} & \bbnum 0 & \text{id}
\end{array}^{\uparrow M}=\text{id}^{\uparrow M}=\text{id}\quad.
\]
To verify the composition law~(\ref{eq:composition-law-of-frun})
for any monad morphisms $\phi_{1}:Q\leadsto R$ and $\phi_{2}:R\leadsto S$,
where $Q$, $R$, $S$ are some monads, denote temporarily by $\psi_{1}$
and $\psi_{2}$ the following monad morphisms:
\begin{align*}
 & \psi_{1}:A+T_{K}^{Q,A}\leadsto A+T_{K}^{R,A}\quad,\quad\quad\psi_{1}\triangleq\,\begin{array}{|c||cc|}
 & A & T_{K}^{R,A}\\
\hline A & \text{id} & \bbnum 0\\
T_{K}^{Q,A} & \bbnum 0 & \text{frun}_{K}^{Q,R}(\phi_{1})
\end{array}\quad,\\
 & \psi_{2}:A+T_{K}^{R,A}\leadsto A+T_{K}^{S,A}\quad,\quad\quad\psi_{2}\triangleq\,\begin{array}{|c||cc|}
 & A & T_{K}^{S,A}\\
\hline A & \text{id} & \bbnum 0\\
T_{K}^{R,A} & \bbnum 0 & \text{frun}_{K}^{R,S}(\phi_{2})
\end{array}\quad.
\end{align*}
With these notations, we write the left side of the functor composition
law:
\begin{align*}
{\color{greenunder}\text{composition law of }\text{frun}_{L}:}\quad & \text{frun}_{L}^{Q,R}(\phi_{1})\bef\text{frun}_{L}^{R,S}(\phi_{2})=\psi_{1}^{\uparrow Q}\bef\gunderline{\phi_{1}\bef\psi_{2}^{\uparrow R}}\bef\phi_{2}\\
{\color{greenunder}\text{naturality of }\phi_{1}:}\quad & =\psi_{1}^{\uparrow Q}\bef\psi_{2}^{\uparrow Q}\bef\phi_{1}\bef\phi_{2}=(\psi_{1}\bef\psi_{2})^{\uparrow Q}\bef\phi\bef\phi_{2}\quad.
\end{align*}
Compute the composition $\psi_{1}\bef\psi_{2}$ separately, using
the composition law of $\text{frun}_{K}$:
\begin{align*}
 & \psi_{1}\bef\psi_{2}=\,\begin{array}{|c||cc|}
 & A & T_{K}^{R,A}\\
\hline A & \text{id} & \bbnum 0\\
T_{K}^{Q,A} & \bbnum 0 & \text{frun}_{K}^{Q,R}(\phi_{1})
\end{array}\,\bef\,\begin{array}{|c||cc|}
 & A & T_{K}^{S,A}\\
\hline A & \text{id} & \bbnum 0\\
T_{K}^{R,A} & \bbnum 0 & \text{frun}_{K}^{R,S}(\phi_{2})
\end{array}\\
{\color{greenunder}\text{matrix composition}:}\quad & =\,\begin{array}{|c||cc|}
 & A & T_{K}^{S,A}\\
\hline A & \text{id} & \bbnum 0\\
T_{K}^{Q,A} & \bbnum 0 & \gunderline{\text{frun}_{K}^{Q,R}(\phi_{1})\bef\text{frun}_{K}^{R,S}\!(\phi_{2})}
\end{array}\,=\,\begin{array}{|c||cc|}
 & A & T_{K}^{S,A}\\
\hline A & \text{id} & \bbnum 0\\
T_{K}^{Q,A} & \bbnum 0 & \text{frun}_{K}^{Q,S}(\phi_{1}\bef\phi_{2})
\end{array}\quad.
\end{align*}
We can now finish verifying the composition law:
\begin{align*}
 & \text{frun}_{L}^{Q,R}(\phi_{1})\bef\text{frun}_{L}^{R,S}(\phi_{2})=(\psi_{1}\bef\psi_{2})^{\uparrow Q}\bef\phi_{1}\bef\phi_{2}\\
 & =\,\begin{array}{|c||cc|}
 & A & T_{K}^{S,A}\\
\hline A & \text{id} & \bbnum 0\\
T_{K}^{Q,A} & \bbnum 0 & \text{frun}_{K}^{Q,S}(\phi_{1}\bef\phi_{2})
\end{array}^{\uparrow Q}\bef\phi_{1}\bef\phi_{2}=\text{frun}_{L}^{Q,S}(\phi_{1}\bef\phi_{2})\quad.
\end{align*}

$\square$

The following property is used in the derivation of the base runner
laws:

\subsubsection{Statement \label{subsec:Statement-monad-morphism-composition-theorem}\ref{subsec:Statement-monad-morphism-composition-theorem}}

Assume $M$ and $N$ are two monads such that the functor composition
$M\circ N$ is a monad defined via a \lstinline!swap! function ($\text{sw}_{M,N}:N\circ M\leadsto M\circ N$)
according to Statement~\ref{sec:Statement-swap-laws-to-monad-transformer-first-law}
(where the two monads are denoted by $M$, $N$ instead of $L$, $M$).
Let $\phi:N\leadsto M$ be a monad morphism such that the \lstinline!swap!
function obeys the law~(\ref{eq:swap-special-law-monad-morphism-composition})
shown below. That law can be seen as a weaker version of a monadic
naturality law of $\text{sw}_{M,N}$ with respect to the parameter
$N$ (where the monad $N$ is transformed by $\phi$ to the fixed
monad $M$ rather than to arbitrary new monad):%
\begin{comment}
precarious formatting
\end{comment}

\begin{wrapfigure}{i}{0.32\columnwidth}%
\vspace{-2.3\baselineskip}

\begin{centering}
\[
\xymatrix{\xyScaleY{1.3pc}\xyScaleX{2.8pc}N^{M^{A}}\ar[r]\sp(0.5){\phi}\ar[d]\sp(0.45){\text{sw}_{M,N}\ } & M^{M^{A}}\ar[rd]\sp(0.5){\ \text{ftn}_{M}}\\
M^{N^{A}}\ar[r]\sp(0.5){\phi^{\uparrow M}} & M^{M^{A}}\ar[r]\sp(0.5){\text{ftn}_{M}} & M^{A}
}
\]
\par\end{centering}
\vspace{0\baselineskip}
\end{wrapfigure}%

~\vspace{-0.4\baselineskip}
\begin{equation}
\phi\bef\text{ftn}_{M}=\text{sw}_{M,N}\bef\phi^{\uparrow M}\bef\text{ftn}_{M}\quad.\label{eq:swap-special-law-monad-morphism-composition}
\end{equation}

Then the function $\phi^{\uparrow M}\bef\text{ftn}_{M}$ is a monad
morphism $M\circ N\leadsto M$. 

\subparagraph{Proof}

We need to check the laws of the monad morphism:
\begin{align*}
{\color{greenunder}\text{identity law}:}\quad & \text{pu}_{M\circ N}\bef\phi^{\uparrow M}\bef\text{ftn}_{M}\overset{?}{=}\text{pu}_{M}\quad,\\
{\color{greenunder}\text{composition law}:}\quad & \text{ftn}_{M\circ N}\bef\phi^{\uparrow M}\bef\text{ftn}_{M}\overset{?}{=}\phi^{\uparrow M}\bef\text{ftn}_{M}\bef(\phi^{\uparrow M}\bef\text{ftn}_{M})^{\uparrow M}\bef\text{ftn}_{M}\quad.
\end{align*}

To verify the identity law:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{pu}_{M}:}\quad & \text{pu}_{M\circ N}\bef\phi^{\uparrow M}\bef\text{ftn}_{M}=\text{pu}_{N}\bef\gunderline{\text{pu}_{M}\bef\phi^{\uparrow M}}\bef\text{ftn}_{M}\\
 & =\gunderline{\text{pu}_{N}\bef\phi}\bef\gunderline{\text{pu}_{M}\bef\text{ftn}_{M}}=\text{pu}_{M}\bef\text{id}=\text{pu}_{M}\quad.
\end{align*}

To verify the composition law, begin with its left-hand side:
\begin{align*}
{\color{greenunder}\text{left-hand side}:}\quad & \text{ftn}_{M\circ N}\bef\phi^{\uparrow M}\bef\text{ftn}_{M}=\text{sw}^{\uparrow M}\bef\text{ftn}_{M}\bef\gunderline{\text{ftn}_{N}^{\uparrow M}\bef\phi^{\uparrow M}}\bef\text{ftn}_{M}\\
{\color{greenunder}\text{composition law of }\phi:}\quad & =\text{sw}^{\uparrow M}\bef\text{ftn}_{M}\bef\big(\phi\bef\phi^{\uparrow M}\bef\text{ftn}_{M}\big)^{\uparrow M}\bef\text{ftn}_{M}\quad.
\end{align*}
In order to use the law~(\ref{eq:swap-special-law-monad-morphism-composition}),
we need to move $\phi$ towards $\text{sw}^{\uparrow M}$ in the composition
and to replace $\text{ftn}_{M}$ by $\text{ftn}_{M}^{\uparrow M}$.
To achieve that, we repeatedly use $\text{ftn}_{M}$\textsf{'}s laws of naturality
and associativity:
\begin{align*}
 & \text{sw}^{\uparrow M}\bef\gunderline{\text{ftn}_{M}\bef\big(\phi}\bef\phi^{\uparrow M}\bef\gunderline{\text{ftn}_{M}\big)^{\uparrow M}\bef\text{ftn}_{M}}=\text{sw}^{\uparrow M}\bef\phi^{\uparrow M\uparrow M}\bef\text{ftn}_{M}\bef\gunderline{\phi^{\uparrow M\uparrow M}\bef\text{ftn}_{M}}\bef\text{ftn}_{M}\\
 & =\big(\text{sw}\bef\phi^{\uparrow M}\big)^{\uparrow M}\bef\gunderline{\text{ftn}_{M}\bef\text{ftn}_{M}}\bef\phi^{\uparrow M}\bef\text{ftn}_{M}=\gunderline{\big(\text{sw}\bef\phi^{\uparrow M}\big)^{\uparrow M}\bef\text{ftn}_{M}^{\uparrow M}}\bef\text{ftn}_{M}\bef\phi^{\uparrow M}\bef\text{ftn}_{M}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:swap-special-law-monad-morphism-composition})}:}\quad & =\big(\phi\bef\gunderline{\text{ftn}_{M}\big)^{\uparrow M}\bef\text{ftn}_{M}}\bef\phi^{\uparrow M}\bef\text{ftn}_{M}=\phi^{\uparrow M}\bef\text{ftn}_{M}\bef\text{ftn}_{M}\bef\phi^{\uparrow M}\bef\text{ftn}_{M}\quad.
\end{align*}
Now we can rewrite the right-hand side of the law and make it equal
to the last expression:
\begin{align*}
{\color{greenunder}\text{right-hand side}:}\quad & \phi^{\uparrow M}\bef\text{ftn}_{M}\bef(\phi^{\uparrow M}\bef\gunderline{\text{ftn}_{M})^{\uparrow M}\bef\text{ftn}_{M}}=\phi^{\uparrow M}\bef\text{ftn}_{M}\bef\gunderline{\phi^{\uparrow M\uparrow M}\bef\text{ftn}_{M}}\bef\text{ftn}_{M}\\
 & =\phi^{\uparrow M}\bef\text{ftn}_{M}\bef\text{ftn}_{M}\bef\phi^{\uparrow M}\bef\text{ftn}_{M}\quad.
\end{align*}


\paragraph{Base runner laws}

Given any base runner $\text{brun}_{K}$ for the monad transformer
$T_{K}$, we define the base runner $\text{brun}_{L}$ through the
special runner $\theta_{P}:P^{A}\rightarrow M^{A}$ that we implement
through $\text{brun}_{K}$:
\begin{equation}
\text{brun}_{L}:M^{A+T_{K}^{M,A}}\rightarrow M^{A}\quad,\quad\quad\text{brun}_{L}\triangleq\theta_{P}^{\uparrow M}\bef\text{ftn}_{M}\quad,\quad\quad\theta_{P}\triangleq\,\begin{array}{|c||c|}
 & M^{A}\\
\hline A & \text{pu}_{M}\\
T_{K}^{M,A} & \text{brun}_{K}
\end{array}\quad.\label{eq:def-of-brun-and-theta-for-free-pointed}
\end{equation}
The runner $\text{brun}_{L}$ is not purely compositional since $L\triangleq M\circ P$
contains the monad $P$ that again depends on $M$. So, we cannot
use the proofs in Statement~\ref{subsec:Statement-monad-transformer-runner-laws-from-swap},
and the monad morphism laws and the non-degeneracy law of $\text{brun}_{L}$
need to be verified separately.

Note that $\theta_{P}:P\leadsto M$ is a monad morphism by Exercise~\ref{par:Exercise-mt-3-2-1}.

To show that $\text{brun}_{L}$ is a monad morphism, we will use Statement~\ref{subsec:Statement-monad-morphism-composition-theorem}
where we use the monad $P^{A}\triangleq A+N^{A}$ instead of $L^{A}$.
It remains to check the properties required by Statement~\ref{subsec:Statement-monad-morphism-composition-theorem}.
The required monad morphism $\phi$ is $\theta_{P}:P\leadsto M$.
The special law of \lstinline!swap! has the following form: 
\[
\theta_{P}\bef\text{ftn}_{M}\overset{?}{=}\text{sw}\bef\theta_{P}^{\uparrow M}\bef\text{ftn}_{M}\quad.
\]
Let us verify this law using Eq.~(\ref{eq:def-of-swap-for-free-pointed-monad-transformer})
and the definition~(\ref{eq:def-of-brun-and-theta-for-free-pointed})
of $\theta_{P}$:
\begin{align*}
{\color{greenunder}\text{expect to equal }\theta_{P}\bef\text{ftn}_{M}:}\quad & \text{sw}\bef\theta_{P}^{\uparrow M}\bef\text{ftn}_{M}=\,\begin{array}{|c||c|}
 & M^{A}\\
\hline M^{A} & \gunderline{\text{pu}_{P}^{\uparrow M}\bef\theta_{P}^{\uparrow M}}\bef\text{ftn}_{M}\\
N^{M^{A}} & (t\rightarrow\bbnum 0^{:A}+\text{merge}\,(t))\bef\gunderline{\text{pu}_{M}\bef\theta_{P}^{\uparrow M}}\bef\text{ftn}_{M}
\end{array}\\
{\color{greenunder}\text{identity law of }\theta_{P}:}\quad & =\,\begin{array}{|c||c|}
 & M^{A}\\
\hline M^{A} & \gunderline{\text{pu}_{M}^{\uparrow M}\bef\text{ftn}_{M}}\\
N^{M^{A}} & (t\rightarrow\bbnum 0^{:A}+\text{merge}\,(t))\bef\theta_{P}\bef\gunderline{\text{pu}_{M}\bef\text{ftn}_{M}}
\end{array}\\
{\color{greenunder}\text{identity laws of }M:}\quad & =\,\,\begin{array}{|c||c|}
 & M^{A}\\
\hline M^{A} & \text{id}\\
N^{M^{A}} & (t\rightarrow\gunderline{\bbnum 0^{:A}+\text{merge}\,(t))\bef\theta_{P}}
\end{array}\,=\,\begin{array}{|c||c|}
 & M^{A}\\
\hline M^{A} & \text{id}\\
N^{M^{A}} & \text{merge}\bef\text{brun}_{K}
\end{array}\quad.
\end{align*}
Write out $\theta_{P}\bef\text{ftn}_{M}$ in matrix form:
\begin{align*}
 & \theta_{P}\bef\text{ftn}_{M}=\,\begin{array}{|c||c|}
 & M^{A}\\
\hline M^{A} & \text{pu}_{M}\bef\text{ftn}_{M}\\
N^{M^{A}} & \text{brun}_{K}\bef\text{ftn}_{M}
\end{array}\,=\,\begin{array}{|c||c|}
 & M^{A}\\
\hline M^{A} & \text{id}\\
N^{M^{A}} & \text{brun}_{K}\bef\text{ftn}_{M}
\end{array}\quad.
\end{align*}
The remaining difference is between the following functions of type
$N^{M^{A}}\rightarrow M^{A}$:
\begin{align*}
 & \text{merge}\bef\text{brun}_{K}\overset{?}{=}\text{brun}_{K}\bef\text{ftn}_{M}\quad,\\
{\color{greenunder}\text{or, using the definition of }\text{merge}:}\quad & \text{flift}_{K}^{\uparrow N}\bef\text{ftn}_{N}\bef\text{brun}_{K}\overset{?}{=}\text{brun}_{K}\bef\text{ftn}_{M}\quad.
\end{align*}
The monad morphism laws of $\text{brun}_{K}$ allow us to prove this
equation:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{brun}_{K}\bef\text{ftn}_{M}:}\quad & \text{flift}_{K}^{\uparrow N}\bef\gunderline{\text{ftn}_{N}\bef\text{brun}_{K}}=\gunderline{\text{flift}_{K}^{\uparrow N}\bef\text{brun}_{K}^{\uparrow N}}\bef\text{brun}_{K}\bef\text{ftn}_{M}\\
{\color{greenunder}\text{non-degeneracy law of }\text{brun}_{K}:}\quad & =\text{brun}_{K}\bef\text{ftn}_{M}\quad.
\end{align*}
This concludes the proof of monad morphism laws of $\text{brun}_{L}$.

To verify the non-degeneracy law, which is an equation between functions
of type $M^{A}\rightarrow M^{A}$:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{id}:}\quad & \text{flift}_{L}\bef\text{brun}_{L}=\text{pu}_{P}^{\uparrow M}\bef\text{brun}_{L}=\gunderline{\text{pu}_{P}^{\uparrow M}\bef\theta_{P}^{\uparrow M}}\bef\text{ftn}_{M}=\gunderline{\text{pu}_{M}^{\uparrow M}\bef\text{ftn}_{M}}=\text{id}\quad.
\end{align*}


\paragraph{Monadic naturality laws}

The monadic naturality law of $\text{flift}_{L}$ is written as
\begin{align*}
 & \text{flift}_{L}\bef\text{frun}_{L}(\phi)\overset{?}{=}\phi\bef\text{flift}_{L}\quad,\\
{\color{greenunder}\text{or, using definitions of }\text{flift}_{L}\text{ and }\text{frun}_{L}:}\quad & \text{pu}_{P}^{\uparrow M}\bef\,\begin{array}{|c||cc|}
 & A & T_{K}^{M^{\prime},A}\\
\hline A & \text{id} & \bbnum 0\\
T_{K}^{M,A} & \bbnum 0 & \text{frun}_{K}^{M,M^{\prime}}\!(\phi)
\end{array}^{\uparrow M}\bef\phi\overset{?}{=}\phi\bef\text{pu}_{P}^{\uparrow M^{\prime}}\quad.
\end{align*}
This should hold for any monad morphism $\phi^{:M\leadsto M^{\prime}}$.
Simplify the expression under $^{\uparrow M}$ separately:
\begin{align*}
 & \text{pu}_{P}\bef\,\begin{array}{|c||cc|}
 & A & T_{K}^{M^{\prime},A}\\
\hline A & \text{id} & \bbnum 0\\
T_{K}^{M,A} & \bbnum 0 & \text{frun}_{K}^{M,M^{\prime}}\!(\phi)
\end{array}\,=(a\rightarrow a+\bbnum 0^{:T_{K}^{M,A}})\bef\,\begin{array}{|c||cc|}
 & A & T_{K}^{M^{\prime},A}\\
\hline A & \text{id} & \bbnum 0\\
T_{K}^{M,A} & \bbnum 0 & \text{frun}_{K}^{M,M^{\prime}}\!(\phi)
\end{array}\,=a\rightarrow a+\bbnum 0\quad.
\end{align*}
So, we can transform the left-hand side of the law and obtain the
right-hand side:
\begin{align*}
 & \text{flift}_{L}\bef\text{frun}_{L}(\phi)=(a\rightarrow a+\bbnum 0)^{\uparrow M}\bef\phi=\gunderline{\text{pu}_{P}^{\uparrow M}\bef\phi}=\phi\bef\text{pu}_{P}^{\uparrow M^{\prime}}\quad.
\end{align*}

The monadic naturality law of $\text{brun}_{L}$ is
\[
\text{brun}_{L}\bef\phi\overset{?}{=}\text{frun}_{L}(\phi)\bef\text{brun}_{L}\quad.
\]
Rewrite the right-hand side using the definitions of $\text{brun}_{L}$
and $\text{frun}_{L}$:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{brun}_{L}\bef\phi:}\quad & \text{frun}_{L}(\phi)\bef\text{brun}_{L}=\,\begin{array}{|c||cc|}
 & A & T_{K}^{M^{\prime},A}\\
\hline A & \text{id} & \bbnum 0\\
T_{K}^{M,A} & \bbnum 0 & \text{frun}_{K}^{M,M^{\prime}}\!(\phi)
\end{array}^{\uparrow M}\bef\gunderline{\phi\bef\theta_{P^{\prime}}^{\uparrow M^{\prime}}}\bef\text{ftn}_{M^{\prime}}\\
{\color{greenunder}\text{naturality law of }\phi:}\quad & =\,\begin{array}{|c||cc|}
 & A & T_{K}^{M^{\prime},A}\\
\hline A & \text{id} & \bbnum 0\\
T_{K}^{M,A} & \bbnum 0 & \text{frun}_{K}^{M,M^{\prime}}\!(\phi)
\end{array}^{\uparrow M}\bef\theta_{P^{\prime}}^{\uparrow M}\bef\phi\bef\text{ftn}_{M^{\prime}}\quad.
\end{align*}
Rewrite the expression under $^{\uparrow M}$ separately:
\begin{align*}
 & \begin{array}{|c||cc|}
 & A & T_{K}^{M^{\prime},A}\\
\hline A & \text{id} & \bbnum 0\\
T_{K}^{M,A} & \bbnum 0 & \text{frun}_{K}^{M,M^{\prime}}\!(\phi)
\end{array}\,\bef\theta_{P^{\prime}}=\,\begin{array}{|c||cc|}
 & A & T_{K}^{M^{\prime},A}\\
\hline A & \text{id} & \bbnum 0\\
T_{K}^{M,A} & \bbnum 0 & \text{frun}_{K}^{M,M^{\prime}}\!(\phi)
\end{array}\,\bef\,\begin{array}{|c||c|}
 & M^{\prime A}\\
\hline A & \text{pu}_{M^{\prime}}\\
T_{K}^{M^{\prime},A} & \text{brun}_{K}
\end{array}\,\\
 & =\,\begin{array}{|c||c|}
 & M^{\prime A}\\
\hline A & \text{pu}_{M^{\prime}}\\
T_{K}^{M,A} & \gunderline{\text{frun}_{K}^{M,M^{\prime}}\!(\phi)\bef\text{brun}_{K}}
\end{array}\,=\,\begin{array}{|c||c|}
 & M^{\prime A}\\
\hline A & \gunderline{\text{pu}_{M^{\prime}}}\\
T_{K}^{M,A} & \text{brun}_{K}\bef\phi
\end{array}\\
 & =\,\,\begin{array}{|c||c|}
 & M^{\prime A}\\
\hline A & \text{pu}_{M}\bef\phi\\
T_{K}^{M,A} & \text{brun}_{K}\bef\phi
\end{array}=\,\begin{array}{|c||c|}
 & M^{A}\\
\hline A & \text{pu}_{M}\\
T_{K}^{M,A} & \text{brun}_{K}
\end{array}\bef\phi=\theta_{P}\bef\phi\quad.
\end{align*}
Here we assumed that $\text{brun}_{K}$ obeys its monadic naturality
law. So, we can now write
\begin{align*}
 & \begin{array}{|c||cc|}
 & A & T_{K}^{M^{\prime},A}\\
\hline A & \text{id} & \bbnum 0\\
T_{K}^{M,A} & \bbnum 0 & \text{frun}_{K}^{M,M^{\prime}}\!(\phi)
\end{array}^{\uparrow M}\bef\theta_{P^{\prime}}^{\uparrow M}\bef\phi\bef\text{ftn}_{M^{\prime}}=\theta_{P}^{\uparrow M}\bef\gunderline{\phi^{\uparrow M}\bef\phi\bef\text{ftn}_{M^{\prime}}}\\
{\color{greenunder}\text{composition law of }\phi:}\quad & =\gunderline{\theta_{P}^{\uparrow M}\bef\text{ftn}_{M}}\bef\phi=\text{brun}_{L}\bef\phi\quad.
\end{align*}

This derivation concludes the proof of the laws of the free pointed
monad transformer.

\section{Transformers for recursive monads}

\subsection{Transformer for free monads. Proofs}

The free monad (denoted by $\text{Free}^{F,\bullet}$) on a given
functor $F$ is the following recursive type constructor:
\[
\text{Free}^{F,A}\triangleq A+F^{\text{Free}^{F,A}}\quad.
\]
Its monad transformer (denoted by $T_{\text{Free}}^{M,\bullet}$)
is also defined recursively:
\[
T_{\text{Free}}^{M,A}\triangleq M^{A+F^{T_{\text{Free}}^{M,A}}}\quad.
\]
For brevity, we omit the superscript $F$ in $\text{Free}^{F}$, since
the functor $F$ will be fixed throughout the derivations. When the
foreign monad $M$ is also fixed, we will denote $T_{\text{Free}}^{M,A}$
simply by $T^{A}$.

\subsubsection{Statement \label{subsec:Statement-free-monad-transformer}\ref{subsec:Statement-free-monad-transformer}}

$T_{\text{Free}}$ is a lawful monad transformer.

\subparagraph{Proof}

We need to define the methods required of a monad transformer and
verify all the laws. 

\paragraph{Monad laws}

The recursively defined type of $T_{\text{Free}}^{M,A}$ contains
infinitely many nested layers of the monad $M$ composed with the
functor $F$. We use the \textsf{``}unrolling trick\textsf{''}\index{unrolling trick for recursive types}
to express $T_{\text{Free}}$ through simpler types. We may write
$T_{\text{Free}}$ as an \textsf{``}infinite\textsf{''} type expression,
\[
T_{\text{Free}}^{M}=M\circ\left(\text{Id}+F\circ M\circ\left(\text{Id}+F\circ M\circ(\text{Id}+...)\right)\right)\quad.
\]
If we denote by $L$ the type constructor defined recursively by
\[
L^{A}\triangleq A+F^{M^{L^{A}}}=A+F^{M^{A+F^{M^{A+...}}}}\quad,
\]
or equivalently by $L^{A}\triangleq\text{Free}^{F\circ M,A}$, we
may express $T_{\text{Free}}^{M,A}$ as
\[
T_{\text{Free}}^{M,A}=M^{L^{A}}\quad,\quad\quad T_{\text{Free}}^{M}=M\circ L=M\circ\text{Free}^{F\circ M}\quad.
\]
Since $\text{Free}^{P}$ is a monad for any functor $P$, in particular
for the functor $P\triangleq F\circ M$, it follows that $L$ is a
monad. It remains to show that the composition $M\circ L$ is also
a monad. This resembles the situation with the composed-inside monad
transformers having a base monad $L$ and a foreign monad $M$. A
significant difference is that the monad $L$ also depends on the
foreign monad $M$. That difference will play a role in proofs of
laws that involve changing the foreign monad. But in this part of
the proof, the foreign monad $M$ is fixed throughout the derivation. 

Similarly to the case of composed-inside transformers, we define a
\lstinline!swap! function:
\begin{equation}
\text{sw}:L^{M^{A}}\rightarrow M^{L^{A}}\quad,\quad\quad\text{sw}\triangleq\,\begin{array}{|c||c|}
 & M^{A+\left(F\circ M\circ L\right)^{A}}\\
\hline M^{A} & (a^{:A}\rightarrow a+\bbnum 0^{:(F\circ M\circ L)^{A}})^{\uparrow M}\\
\left(F\circ M\circ L\circ M\right)^{A} & \overline{\text{sw}}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0^{:A}+p)\bef\text{pu}_{M}
\end{array}\quad.\label{eq:definition-of-swap-for-free-monad-transformer}
\end{equation}
The upper row of the matrix contains the function $a\rightarrow a+\bbnum 0$,
which is the \lstinline!pure! method of the monad $L$ (denoted by
$\text{pu}_{L}$). The lower row of the matrix contains a composition
of four functions, the first of which being $\overline{\text{sw}}$,
the recursive call to \lstinline!swap!. To illustrate the types involved
in the composition:
\[
\xymatrix{\xyScaleY{0.2pc}\xyScaleX{4.0pc}F^{M^{L^{M^{A}}}}\ar[r]\sp(0.5){\overline{\text{sw}}^{\uparrow M\uparrow F}} & F^{M^{M^{L^{A}}}}\ar[r]\sp(0.5){\text{ftn}_{M}^{\uparrow F}} & F^{M^{L^{A}}}\ar[r]\sp(0.5){p\rightarrow\bbnum 0^{:A}+p} & A+F^{M^{L^{A}}}\ar[r]\sp(0.5){\text{pu}_{M}} & M^{A+F^{M^{L^{A}}}}}
\]
 The required methods \lstinline!pure! and \lstinline!flatten! of
the monad $T\triangleq M\circ L$ are defined by
\[
\text{pu}_{T}\triangleq\text{pu}_{L}\bef\text{pu}_{M}\quad,\quad\quad\text{ftn}_{T}\triangleq\text{sw}^{\uparrow M}\bef\text{ftn}_{M}\bef\text{ftn}_{L}^{\uparrow M}\quad.
\]

To prove that the composition $T\triangleq M\circ L$ is a lawful
monad, we use Statement~\ref{sec:Statement-swap-laws-to-monad-transformer-first-law}
with the monads $L$ and $M$ exchanged. That statement requires \lstinline!swap!
to satisfy its four laws:
\begin{align*}
{\color{greenunder}\text{outer identity}:}\quad & \text{pu}_{M}^{\uparrow L}\bef\text{sw}=\text{pu}_{M}\quad,\\
{\color{greenunder}\text{inner identity}:}\quad & \text{pu}_{L}\bef\text{sw}=\text{pu}_{L}^{\uparrow M}\quad,\\
{\color{greenunder}\text{outer interchange}:}\quad & \text{ftn}_{M}^{\uparrow L}\bef\text{sw}=\text{sw}\bef\text{sw}^{\uparrow M}\bef\text{ftn}_{M}\quad,\\
{\color{greenunder}\text{inner interchange}:}\quad & \text{ftn}_{L}\bef\text{sw}=\text{sw}^{\uparrow L}\bef\text{sw}\bef\text{ftn}_{L}^{\uparrow M}\quad.
\end{align*}
To verify these laws, we need the code for the lifting ($^{\uparrow L}$)
as well as for the methods $\text{pu}_{L}$ and $\text{ftn}_{L}$.
Since $L$ is a free monad on the functor $F\circ M$, we can adapt
the code from Statement~\ref{subsec:Statement-monad-construction-4}:
\begin{align*}
 & (f^{:A\rightarrow B})^{\uparrow L}=\,\begin{array}{|c||cc|}
 & B & F^{M^{L^{B}}}\\
\hline A & f & \bbnum 0\\
F^{M^{L^{A}}} & \bbnum 0 & \big(f^{\overline{\uparrow L}}\big)^{\uparrow M\uparrow F}
\end{array}\quad,\\
\text{pu}_{L}\triangleq\,\begin{array}{|c||cc|}
 & A & F^{M^{L^{A}}}\\
\hline A & \text{id} & \bbnum 0
\end{array}\quad, & \quad\quad\text{ftn}_{L}^{:L^{L^{A}}\rightarrow L^{A}}\triangleq\,\begin{array}{|c||cc|}
 & A & F^{M^{L^{A}}}\\
\hline A & \text{id} & \bbnum 0\\
F^{M^{L^{A}}} & \bbnum 0 & \text{id}\\
F^{M^{L^{L^{A}}}} & \bbnum 0 & \overline{\text{ftn}}_{L}^{\uparrow M\uparrow F}
\end{array}\quad.
\end{align*}

In the calculations, we will omit type annotations for brevity. To
verify the outer identity law:
\begin{align*}
 & \text{pu}_{M}^{\uparrow L}\bef\text{sw}=\,\begin{array}{||cc|}
\text{pu}_{M} & \bbnum 0\\
\bbnum 0 & \big(\text{pu}_{M}^{\overline{\uparrow L}}\big)^{\uparrow M\uparrow F}
\end{array}\,\bef\,\begin{array}{||c|}
\big(a^{:A}\rightarrow a+\bbnum 0^{:(F\circ M\circ L)^{A}}\big)^{\uparrow M}\\
\overline{\text{sw}}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0^{:A}+p)\bef\text{pu}_{M}
\end{array}\\
 & =\,\begin{array}{||c|}
\gunderline{\text{pu}_{M}}\bef\big(a^{:A}\rightarrow a+\bbnum 0^{:(F\circ M\circ L)^{A}}\big)^{\gunderline{\uparrow M}}\\
\gunderline{\big(\text{pu}_{M}^{\overline{\uparrow L}}\big)^{\uparrow M\uparrow F}\bef\overline{\text{sw}}^{\uparrow M\uparrow F}}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0+p)\bef\text{pu}_{M}
\end{array}\,=\,\begin{array}{||c|}
\big(a^{:A}\rightarrow a+\bbnum 0^{:(F\circ M\circ L)^{A}}\big)\bef\gunderline{\text{pu}_{M}}\\
\big(\gunderline{\text{pu}_{M}^{\overline{\uparrow L}}\bef\overline{\text{sw}}}\big)^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0+p)\bef\gunderline{\text{pu}_{M}}
\end{array}\\
 & =\,\,\begin{array}{||c|}
a^{:A}\rightarrow a+\bbnum 0^{:(F\circ M\circ L)^{A}}\\
\big(\gunderline{\text{pu}_{M}^{\uparrow M}\bef\text{ftn}_{M}}\big)^{\uparrow F}\bef(p\rightarrow\bbnum 0+p)
\end{array}\,\bef\text{pu}_{M}=\,\begin{array}{|c||c|}
 & A+F^{M^{L^{A}}}\\
\hline A & a\rightarrow a+\bbnum 0\\
F^{M^{L^{A}}} & p\rightarrow\bbnum 0^{:A}+p
\end{array}\,\bef\text{pu}_{M}=\text{id}\bef\text{pu}_{M}=\text{pu}_{M}\quad.
\end{align*}

To verify the inner identity law:
\[
\text{pu}_{L}\bef\text{sw}=\,\begin{array}{||cc|}
\text{id} & \bbnum 0\end{array}\,\bef\,\begin{array}{||c|}
\big(a^{:A}\rightarrow a+\bbnum 0^{:(F\circ M\circ L)^{A}}\big)^{\uparrow M}\\
\overline{\text{sw}}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0^{:A}+p)\bef\text{pu}_{M}
\end{array}\,=\big(a^{:A}\rightarrow a+\bbnum 0^{:(F\circ M\circ L)^{A}}\big)^{\uparrow M}=\text{pu}_{L}^{\uparrow M}\quad.
\]

To verify the outer interchange law, write the two sides of the law
separately:
\begin{align*}
{\color{greenunder}\text{left-hand side}:}\quad & \text{ftn}_{M}^{\uparrow L}\bef\text{sw}=\,\begin{array}{||cc|}
\text{ftn}_{M} & \bbnum 0\\
\bbnum 0 & \big(\text{ftn}_{M}^{\overline{\uparrow L}}\big)^{\uparrow M\uparrow F}
\end{array}\,\bef\,\begin{array}{||c|}
\big(a^{:A}\rightarrow a+\bbnum 0^{:(F\circ M\circ L)^{A}}\big)^{\uparrow M}\\
\overline{\text{sw}}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0^{:A}+p)\bef\text{pu}_{M}
\end{array}\\
 & \quad=\,\begin{array}{||c|}
\text{ftn}_{M}\bef\text{pu}_{L}^{\uparrow M}\\
\big(\text{ftn}_{M}^{\overline{\uparrow L}}\big)^{\uparrow M\uparrow F}\bef\overline{\text{sw}}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0^{:A}+p)\bef\text{pu}_{M}
\end{array}\quad,\\
{\color{greenunder}\text{right-hand side}:}\quad & \text{sw}\bef\text{sw}^{\uparrow M}\bef\text{ftn}_{M}=\,\begin{array}{||c|}
\gunderline{\text{pu}_{L}^{\uparrow M}\bef\text{sw}^{\uparrow M}}\bef\text{ftn}_{M}\\
\overline{\text{sw}}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0^{:A}+p)\bef\gunderline{\text{pu}_{M}\bef\text{sw}^{\uparrow M}}\bef\text{ftn}_{M}
\end{array}\\
 & \quad=\,\begin{array}{||c|}
\gunderline{\text{pu}_{L}^{\uparrow M\uparrow M}\bef\text{ftn}_{M}}\\
\overline{\text{sw}}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0^{:A}+p)\bef\text{sw}\bef\gunderline{\text{pu}_{M}\bef\text{ftn}_{M}}
\end{array}\\
 & \quad=\,\,\begin{array}{||c|}
\text{ftn}_{M}\bef\text{pu}_{L}^{\uparrow M}\\
\overline{\text{sw}}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0^{:A}+p)\bef\text{sw}
\end{array}\quad.
\end{align*}
The remaining difference is in the second rows of the matrices:
\begin{equation}
\big(\text{ftn}_{M}^{\overline{\uparrow L}}\big)^{\uparrow M\uparrow F}\bef\overline{\text{sw}}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0^{:A}+p)\bef\text{pu}_{M}\overset{?}{=}\overline{\text{sw}}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0^{:A}+p)\bef\text{sw}\quad.\label{eq:outer-interchange-free-monad-derivation1}
\end{equation}
Let us rewrite both sides of this expression step by step. By the
inductive assumption, we may use the outer interchange law for the
recursive call to \lstinline!swap!:
\[
\text{ftn}_{M}^{\overline{\uparrow L}}\bef\overline{\text{sw}}=\text{sw}\bef\text{sw}^{\uparrow M}\bef\text{ftn}_{M}\quad.
\]
We can then rewrite the left-hand side of Eq.~(\ref{eq:outer-interchange-free-monad-derivation1})
as
\begin{align*}
 & \gunderline{\big(\text{sw}\bef\text{sw}^{\uparrow M}\bef\text{ftn}_{M}\big)^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}}\bef(p\rightarrow\bbnum 0^{:A}+p)\bef\text{pu}_{M}\\
{\color{greenunder}\text{composition under }^{\uparrow F}:}\quad & =\big(\text{sw}^{\uparrow M}\bef\text{sw}^{\uparrow M\uparrow M}\bef\gunderline{\text{ftn}_{M}^{\uparrow M}\bef\text{ftn}_{M}}\big)^{\uparrow F}\bef(p\rightarrow\bbnum 0^{:A}+p)\bef\text{pu}_{M}\\
{\color{greenunder}\text{associativity law of }\text{ftn}_{M}:}\quad & =\big(\text{sw}^{\uparrow M}\bef\gunderline{\text{sw}^{\uparrow M\uparrow M}\bef\text{ftn}_{M}}\bef\text{ftn}_{M}\big)^{\uparrow F}\bef(p\rightarrow\bbnum 0^{:A}+p)\bef\text{pu}_{M}\\
{\color{greenunder}\text{naturality law of }\text{ftn}_{M}:}\quad & =\big(\text{sw}^{\uparrow M}\bef\text{ftn}_{M}\bef\text{sw}^{\uparrow M}\bef\text{ftn}_{M}\big)^{\uparrow F}\bef(p\rightarrow\bbnum 0^{:A}+p)\bef\text{pu}_{M}\quad.
\end{align*}
We can also compute the expression $(p\rightarrow\bbnum 0^{:A}+p)\bef\text{sw}$
in the right-hand side of Eq.~(\ref{eq:outer-interchange-free-monad-derivation1}):
\begin{align*}
 & (p\rightarrow\bbnum 0+p)\bef\text{sw}=\,\begin{array}{||cc|}
\bbnum 0 & \text{id}\end{array}\,\bef\,\begin{array}{||c|}
\text{pu}_{L}^{\uparrow M}\\
\overline{\text{sw}}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0+p)\bef\text{pu}_{M}
\end{array}\\
 & =(\overline{\text{sw}}^{\uparrow M}\bef\text{ftn}_{M})^{\uparrow F}\bef(p\rightarrow\bbnum 0+p)\bef\text{pu}_{M}\quad.
\end{align*}
Then Eq.~(\ref{eq:outer-interchange-free-monad-derivation1}) becomes
\begin{align*}
 & \big(\text{sw}^{\uparrow M}\bef\text{ftn}_{M}\bef\text{sw}^{\uparrow M}\bef\text{ftn}_{M}\big)^{\uparrow F}\bef(p\rightarrow\bbnum 0+p)\bef\text{pu}_{M}\\
 & \overset{?}{=}\gunderline{\overline{\text{sw}}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}}\bef(\overline{\text{sw}}^{\uparrow M}\bef\text{ftn}_{M})^{\uparrow F}\bef(p\rightarrow\bbnum 0+p)\bef\text{pu}_{M}\\
 & =\big(\text{sw}^{\uparrow M}\bef\text{ftn}_{M}\bef\text{sw}^{\uparrow M}\bef\text{ftn}_{M}\big)^{\uparrow F}\bef(p\rightarrow\bbnum 0+p)\bef\text{pu}_{M}\quad.
\end{align*}
Both sides are now equal.

To verify the inner interchange law, write its two sides separately:
\begin{align*}
{\color{greenunder}\text{left-hand side}:}\quad & \text{ftn}_{L}\bef\text{sw}=\,\begin{array}{|c||cc|}
 & M^{A} & F^{M^{L^{M^{A}}}}\\
\hline M^{A} & \text{id} & \bbnum 0\\
F^{M^{L^{M^{A}}}} & \bbnum 0 & \text{id}\\
F^{M^{L^{L^{M^{A}}}}} & \bbnum 0 & \overline{\text{ftn}}_{L}^{\uparrow M\uparrow F}
\end{array}\,\bef\,\begin{array}{||c|}
\text{pu}_{L}^{\uparrow M}\\
\overline{\text{sw}}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0+p)\bef\text{pu}_{M}
\end{array}\\
 & \quad=\,\begin{array}{|c||c|}
 & M^{A+(F\circ M\circ L\circ M)^{A}}\\
\hline M^{A} & \text{pu}_{L}^{\uparrow M}\\
F^{M^{L^{M^{A}}}} & \overline{\text{sw}}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0+p)\bef\text{pu}_{M}\\
F^{M^{L^{L^{M^{A}}}}} & \overline{\text{ftn}}_{L}^{\uparrow M\uparrow F}\bef\overline{\text{sw}}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0+p)\bef\text{pu}_{M}
\end{array}\quad,\\
{\color{greenunder}\text{right-hand side}:}\quad & \text{sw}^{\uparrow L}\bef\text{sw}\bef\text{ftn}_{L}^{\uparrow M}=\,\begin{array}{|c||cc|}
 & M^{L^{A}} & F^{M^{L^{M^{L^{A}}}}}\\
\hline L^{M^{A}} & \text{sw} & \bbnum 0\\
F^{M^{L^{L^{M^{A}}}}} & \bbnum 0 & \big(\text{sw}^{\overline{\uparrow L}}\big)^{\uparrow M\uparrow F}
\end{array}\,\bef\text{sw}\bef\text{ftn}_{L}^{\uparrow M}\quad.
\end{align*}
In order to compare the resulting matrices, we need to expand the
first row of the last matrix, so that the disjunctive type $L^{M^{A}}$
is represented as $M^{A}+(F\circ M\circ L)^{M^{A}}$. We can then
fill in the matrix elements of \lstinline!swap!:
\begin{align*}
\text{sw}^{\uparrow L} & =\,\begin{array}{|c||cc|}
 & M^{L^{A}} & F^{M^{L^{M^{L^{A}}}}}\\
\hline L^{M^{A}} & \text{sw} & \bbnum 0\\
F^{M^{L^{L^{M^{A}}}}} & \bbnum 0 & \big(\text{sw}^{\overline{\uparrow L}}\big)^{\uparrow M\uparrow F}
\end{array}\\
 & =\,\,\begin{array}{|c||cc|}
 & M^{L^{A}} & F^{M^{L^{M^{L^{A}}}}}\\
\hline M^{A} & \text{pu}_{L}^{\uparrow M} & \bbnum 0\\
F^{M^{L^{M^{A}}}} & \overline{\text{sw}}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0+p)\bef\text{pu}_{M} & \bbnum 0\\
F^{M^{L^{L^{M^{A}}}}} & \bbnum 0 & \big(\text{sw}^{\overline{\uparrow L}}\big)^{\uparrow M\uparrow F}
\end{array}\quad.
\end{align*}
With this matrix, we continue rewriting the right-hand side of the
inner interchange law:
\begin{align*}
 & \text{sw}^{\uparrow L}\bef\text{sw}\bef\text{ftn}_{L}^{\uparrow M}\\
 & =\,\begin{array}{||cc|}
\text{pu}_{L}^{\uparrow M} & \bbnum 0\\
\overline{\text{sw}}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0+p)\bef\text{pu}_{M} & \bbnum 0\\
\bbnum 0 & \big(\text{sw}^{\overline{\uparrow L}}\big)^{\uparrow M\uparrow F}
\end{array}\,\bef\,\begin{array}{||c|}
\text{pu}_{L}^{\uparrow M}\\
\overline{\text{sw}}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0+p)\bef\text{pu}_{M}
\end{array}\,\bef\text{ftn}_{L}^{\uparrow M}\\
 & =\,\,\begin{array}{||c|}
\text{pu}_{L}^{\uparrow M}\bef\gunderline{\text{pu}_{L}^{\uparrow M}\bef\text{ftn}_{L}^{\uparrow M}}\\
\overline{\text{sw}}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0+p)\bef\text{pu}_{M}\bef\gunderline{\text{pu}_{L}^{\uparrow M}\bef\text{ftn}_{L}^{\uparrow M}}\\
\gunderline{\big(\text{sw}^{\overline{\uparrow L}}\big)^{\uparrow M\uparrow F}\bef\overline{\text{sw}}^{\uparrow M\uparrow F}}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0+p)\bef\gunderline{\text{pu}_{M}\bef\text{ftn}_{L}^{\uparrow M}}
\end{array}\\
 & =\,\begin{array}{||c|}
\text{pu}_{L}^{\uparrow M}\\
\overline{\text{sw}}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0+p)\bef\text{pu}_{M}\\
\big(\text{sw}^{\overline{\uparrow L}}\bef\overline{\text{sw}}\big)^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0+p)\bef\text{ftn}_{L}\bef\text{pu}_{M}
\end{array}\quad.
\end{align*}
The remaining difference between the two sides of the law is only
in the last rows of the matrices:
\[
\overline{\text{ftn}}_{L}^{\uparrow M\uparrow F}\bef\overline{\text{sw}}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0+p)\bef\text{pu}_{M}\overset{?}{=}\big(\text{sw}^{\overline{\uparrow L}}\bef\overline{\text{sw}}\big)^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0+p)\bef\text{ftn}_{L}\bef\text{pu}_{M}\quad.
\]
By the inductive assumption, the law already holds for the recursive
call to \lstinline!swap!:
\[
\overline{\text{ftn}}_{L}\bef\overline{\text{sw}}=\text{sw}^{\uparrow L}\bef\text{sw}\bef\text{ftn}_{L}^{\uparrow M}\quad.
\]
This gives the following code for the left-hand side:
\begin{align*}
 & \gunderline{\overline{\text{ftn}}_{L}^{\uparrow M\uparrow F}\bef\overline{\text{sw}}^{\uparrow M\uparrow F}}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0+p)\bef\text{pu}_{M}\\
{\color{greenunder}\text{inductive assumption}:}\quad & =(\text{sw}^{\uparrow L}\bef\text{sw}\bef\gunderline{\text{ftn}_{L}^{\uparrow M})^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}}\bef(p\rightarrow\bbnum 0+p)\bef\text{pu}_{M}\\
{\color{greenunder}\text{naturality of }\text{ftn}_{M}:}\quad & =(\text{sw}^{\uparrow L}\bef\text{sw})^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef\text{ftn}_{L}^{\uparrow M\uparrow F}\bef(p\rightarrow\bbnum 0+p)\bef\text{pu}_{M}\quad.
\end{align*}
The remaining difference between the two sides is
\begin{align*}
 & (\text{sw}^{\uparrow L}\bef\text{sw})^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef\text{ftn}_{L}^{\uparrow M\uparrow F}\bef(p\rightarrow\bbnum 0+p)\bef\text{pu}_{M}\\
 & \overset{?}{=}\big(\text{sw}^{\overline{\uparrow L}}\bef\overline{\text{sw}}\big)^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0+p)\bef\text{ftn}_{L}\bef\text{pu}_{M}\quad.
\end{align*}
Both sides are functions of type $(F\circ M\circ L\circ L\circ M)^{A}\rightarrow M^{L^{A}}$.
We will prove the equality above if we show that the following two
functions of type $(F\circ M\circ L\circ L)^{A}\rightarrow L^{A}$
are equal:
\[
(p\rightarrow\bbnum 0+p)\bef\text{ftn}_{L}\overset{?}{=}\text{ftn}_{L}^{\uparrow M\uparrow F}\bef(p\rightarrow\bbnum 0+p)\quad.
\]
We compute the left-hand side and show that it equals the right-hand
side:
\begin{align*}
 & (p\rightarrow\bbnum 0^{:L^{A}}+p)\bef\text{ftn}_{L}=\,\begin{array}{|c||cc|}
 & L^{A} & (F\circ M\circ L\circ L)^{A}\\
\hline (F\circ M\circ L\circ L)^{A} & \bbnum 0 & \text{id}
\end{array}\,\bef\,\begin{array}{|c||cc|}
 & A & F^{M^{L^{A}}}\\
\hline A & \text{id} & \bbnum 0\\
F^{M^{L^{A}}} & \bbnum 0 & \text{id}\\
F^{M^{L^{L^{A}}}} & \bbnum 0 & \overline{\text{ftn}}_{L}^{\uparrow M\uparrow F}
\end{array}\\
 & =\,\begin{array}{|c||ccc|}
 & A & F^{M^{L^{A}}} & (F\circ M\circ L\circ L)^{A}\\
\hline (F\circ M\circ L\circ L)^{A} & \bbnum 0 & \bbnum 0 & \text{id}
\end{array}\,\bef\,\begin{array}{|c||cc|}
 & A & F^{M^{L^{A}}}\\
\hline A & \text{id} & \bbnum 0\\
F^{M^{L^{A}}} & \bbnum 0 & \text{id}\\
F^{M^{L^{L^{A}}}} & \bbnum 0 & \overline{\text{ftn}}_{L}^{\uparrow M\uparrow F}
\end{array}\\
 & =\,\,\begin{array}{|c||cc|}
 & A & (F\circ M\circ L)^{A}\\
\hline (F\circ M\circ L\circ L)^{A} & \bbnum 0 & \overline{\text{ftn}}_{L}^{\uparrow M\uparrow F}
\end{array}\,=\overline{\text{ftn}}_{L}^{\uparrow M\uparrow F}\bef(p^{:(F\circ M\circ L)^{A}}\rightarrow\bbnum 0^{:A}+p)\quad.
\end{align*}

This concludes the proof of the four laws of \lstinline!swap!. It
follows that $M\circ L$ is a lawful monad.

\paragraph{Identity laws}

Setting $M=\text{Id}$ in the type of $T_{\text{Free}}^{M,A}$, we
get the isomorphism $\text{Id}\circ\text{Free}^{F\circ\text{Id}}\cong\text{Free}^{F}$.

\paragraph{Lifting laws}

The function \lstinline!flift! for $T_{\text{Free}}$ is defined
by
\[
\text{flift}:M^{A}\rightarrow M^{L^{A}}\quad,\quad\quad\text{flift}\triangleq\text{pu}_{L}^{\uparrow M}=(a^{:A}\rightarrow a+\bbnum 0^{:(F\circ M\circ L)^{A}})^{\uparrow M}\quad.
\]
To show that \lstinline!flift! is a monad morphism, we refer to Statement~\ref{subsec:Statement-transformer-lifting-laws-from-swap},
where we need to use \lstinline!blift! instead of \lstinline!flift!
and exchange the monads $L$ and $M$.

\paragraph{Implementation of runners}

Since the transformer $T_{\text{Free}}=M\circ L$ is not purely compositional
(the monad $L$ itself depends on $M$), mapping the monad $M$ to
$M^{\prime}$ via a monad morphism $\phi:M\leadsto M^{\prime}$ requires
us also to map $L$ to $L^{\prime}\triangleq\text{Free}^{F\circ M^{\prime}}$.
Denote that map temporarily by $\psi$; it is a function of $\phi$,
but we will write simply $\psi$ rather than $\psi(\phi)$ for brevity,
since $\phi$ is fixed throughout the derivation. We can implement
$\psi:L^{A}\rightarrow L^{\prime A}$ by the following code matrix:
\begin{equation}
\psi:\text{Free}^{F\circ M,A}\rightarrow\text{Free}^{F\circ M^{\prime},A}\quad,\quad\quad\psi\triangleq\,\begin{array}{|c||cc|}
 & A & (F\circ M^{\prime}\circ L^{\prime})^{A}\\
\hline A & \text{id} & \bbnum 0\\
(F\circ M\circ L)^{A} & \bbnum 0 & \overline{\psi}^{\uparrow M\uparrow F}\bef\phi^{\uparrow F}
\end{array}\quad.\label{eq:free-monad-definition-of-psi}
\end{equation}
Since $\phi$ is a natural transformation, Exercise~\ref{subsec:Exercise-reasoning-1-4-1}(a)
indicates that the map $\phi^{\uparrow F}:F^{M^{A}}\leadsto F^{M^{\prime A}}$
is also a natural transformation, and then Statement~\ref{subsec:Statement-free-monad-monadic-naturality}
shows that $\psi:\text{Free}^{F\circ M}\leadsto\text{Free}^{F\circ M^{\prime}}$
is a monad morphism. The foreign runner $\text{frun}^{M,M^{\prime}}(\phi):T_{\text{Free}}\leadsto T_{\text{Free}}^{\prime}$
is then implemented by
\[
\text{frun}^{M,M^{\prime}}\!:\left(M\leadsto M^{\prime}\right)\rightarrow M^{L^{A}}\rightarrow M^{\prime L^{\prime A}}\!\quad,\quad\text{frun}^{M,M^{\prime}}\!(\phi^{:M\leadsto M^{\prime}})\triangleq\psi^{\uparrow M}\bef\phi\quad.
\]

To implement the base runner, we use the similarity between the two
disjunctive types,
\[
L^{A}\triangleq\text{Free}^{F\circ M,A}=A+F^{M^{\text{Free}^{F\circ M,A}}}=A+(F\circ M\circ L)^{A}\quad\text{ and }\quad\text{Free}^{F,M^{A}}=M^{A}+F^{\text{Free}^{F,M^{A}}}\quad.
\]
The code for the base runner is:
\begin{align*}
 & \text{brun}:(\text{Free}^{F}\leadsto\text{Id})\rightarrow M^{L^{A}}\rightarrow M^{A}\quad,\\
 & \text{brun}\,(\theta^{:\text{Free}^{F}\leadsto\text{Id}})\triangleq\,\begin{array}{|c||cc|}
 & M^{A} & F^{\text{Free}^{F,M^{A}}}\\
\hline A & \text{pu}_{M} & \bbnum 0\\
(F\circ M\circ L)^{A} & \bbnum 0 & (\overline{\text{brun}}\,(\theta)\bef(x^{:M^{A}}\rightarrow x+\bbnum 0^{:F^{\text{Free}^{F,M^{A}}}}))^{\uparrow F}
\end{array}^{\uparrow M}\bef\theta^{\uparrow M}\bef\text{ftn}_{M}\quad.
\end{align*}


\paragraph{Monadic naturality of \texttt{swap}}

When the monad $M$ is replaced by another monad $M^{\prime}$ via
a monad morphism $\phi:M\leadsto M^{\prime}$, the \lstinline!swap!
function with type signature $\text{sw}_{M,L}:L\circ M\leadsto M\circ L$
is replaced by the corresponding function $\text{sw}_{M^{\prime},L^{\prime}}:L^{\prime}\circ M^{\prime}\leadsto M^{\prime}\circ L^{\prime}$.
The function $\text{sw}_{M^{\prime},L^{\prime}}$ has the same code
as $\text{sw}_{M,L}$ except for using the monad parameter $M^{\prime}$
instead of $M$. This monadic naturality property is expressed by
the law analogous to Eq.~(\ref{eq:monadic-naturality-free-pointed-swap}):
\begin{equation}
\text{sw}_{M,L}\bef\psi^{\uparrow M}\bef\phi=\phi^{\uparrow L}\bef\psi\bef\text{sw}_{M^{\prime},L^{\prime}}\quad.\label{eq:monadic-naturality-swap-free-monad}
\end{equation}
To verify this law, compute both sides of Eq.~(\ref{eq:monadic-naturality-swap-free-monad})
separately. Both sides are functions of type $L^{M^{A}}\rightarrow M^{\prime L^{\prime A}}$:
\begin{align*}
{\color{greenunder}\text{left-hand side}:}\quad & \text{sw}_{M,L}\bef\psi^{\uparrow M}\bef\phi=\,\begin{array}{|c||c|}
 & M^{\prime A+\left(F\circ M^{\prime}\circ L^{\prime}\right)^{A}}\\
\hline M^{A} & \gunderline{\text{pu}_{L}^{\uparrow M}\bef\psi^{\uparrow M}}\bef\phi\\
F^{M^{L^{M^{A}}}} & \overline{\text{sw}}_{M,L}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0^{:A}+p)\bef\gunderline{\text{pu}_{M}\bef\psi^{\uparrow M}}\bef\phi
\end{array}\\
 & =\,\begin{array}{|c||c|}
 & M^{\prime A+\left(F\circ M^{\prime}\circ L^{\prime}\right)^{A}}\\
\hline M^{A} & \text{pu}_{L^{\prime}}^{\uparrow M}\bef\phi\\
F^{M^{L^{M^{A}}}} & \overline{\text{sw}}_{M,L}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0^{:A}+p)\bef\psi\bef\text{pu}_{M}\bef\phi
\end{array}\quad,\\
{\color{greenunder}\text{right-hand side}:}\quad & \phi^{\uparrow L}\bef\psi\bef\text{sw}_{M^{\prime},L^{\prime}}\\
 & =\,\begin{array}{|c||cc|}
 & M^{\prime A} & F^{M^{L^{M^{\prime A}}}}\\
\hline M^{A} & \phi & \bbnum 0\\
F^{M^{L^{M^{A}}}} & \bbnum 0 & \big(\phi^{\overline{\uparrow L}}\big)^{\uparrow M\uparrow F}
\end{array}\,\bef\,\begin{array}{|c||cc|}
 & M^{\prime A} & F^{M^{\prime L^{\prime M^{\prime A}}}}\\
\hline M^{\prime A} & \text{id} & \bbnum 0\\
F^{M^{L^{M^{\prime A}}}} & \bbnum 0 & \overline{\psi}^{\uparrow M\uparrow F}\bef\phi^{\uparrow F}
\end{array}\,\bef\text{sw}_{M^{\prime},L^{\prime}}
\end{align*}
\begin{align*}
 & =\,\begin{array}{|c||cc|}
 & M^{\prime A} & F^{M^{\prime L^{\prime M^{\prime A}}}}\\
\hline M^{A} & \phi & \bbnum 0\\
F^{M^{L^{M^{A}}}} & \bbnum 0 & \big(\phi^{\overline{\uparrow L}}\big)^{\uparrow M\uparrow F}\bef\overline{\psi}^{\uparrow M\uparrow F}\bef\phi^{\uparrow F}
\end{array}\bef\,\begin{array}{|c||c|}
 & M^{\prime A+\left(F\circ M^{\prime}\circ L^{\prime}\right)^{A}}\\
\hline M^{\prime A} & \text{pu}_{L^{\prime}}^{\uparrow M^{\prime}}\\
F^{M^{\prime L^{\prime M^{\prime A}}}} & \overline{\text{sw}}_{M^{\prime},L^{\prime}}^{\uparrow M^{\prime}\uparrow F}\bef\text{ftn}_{M^{\prime}}^{\uparrow F}\bef(p\rightarrow\bbnum 0^{:A}+p)\bef\text{pu}_{M^{\prime}}
\end{array}\\
 & =\,\,\begin{array}{|c||c|}
 & M^{\prime A+\left(F\circ M^{\prime}\circ L^{\prime}\right)^{A}}\\
\hline M^{A} & \phi\bef\text{pu}_{L^{\prime}}^{\uparrow M^{\prime}}\\
F^{M^{L^{M^{A}}}} & \big(\phi^{\overline{\uparrow L}}\big)^{\uparrow M\uparrow F}\bef\overline{\psi}^{\uparrow M\uparrow F}\bef\phi^{\uparrow F}\bef\overline{\text{sw}}_{M^{\prime},L^{\prime}}^{\uparrow M^{\prime}\uparrow F}\bef\text{ftn}_{M^{\prime}}^{\uparrow F}\bef(p\rightarrow\bbnum 0^{:A}+p)\bef\text{pu}_{M^{\prime}}
\end{array}\quad.
\end{align*}
The first rows of the two matrices are equal due to naturality of
$\phi$,
\[
\text{pu}_{L^{\prime}}^{\uparrow M}\bef\phi=\phi\bef\text{pu}_{L^{\prime}}^{\uparrow M^{\prime}}\quad.
\]
The remaining difference is in the second rows:
\begin{align}
 & \overline{\text{sw}}_{M,L}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0^{:A}+p)\bef\psi\bef\text{pu}_{M}\bef\phi\nonumber \\
 & \overset{?}{=}\big(\phi^{\overline{\uparrow L}}\big)^{\uparrow M\uparrow F}\bef\overline{\psi}^{\uparrow M\uparrow F}\bef\phi^{\uparrow F}\bef\overline{\text{sw}}_{M^{\prime},L^{\prime}}^{\uparrow M^{\prime}\uparrow F}\bef\text{ftn}_{M^{\prime}}^{\uparrow F}\bef(p\rightarrow\bbnum 0^{:A}+p)\bef\text{pu}_{M^{\prime}}\quad.\label{eq:monadic-naturality-swap-free-monad-derivation1}
\end{align}
Transform the left-hand side of Eq.~(\ref{eq:monadic-naturality-swap-free-monad-derivation1}):
\begin{align*}
 & \overline{\text{sw}}_{M,L}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0+p)\bef\psi\bef\gunderline{\text{pu}_{M}\bef\phi}\\
 & =\overline{\text{sw}}_{M,L}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef\,\begin{array}{||cc|}
\bbnum 0 & \text{id}\end{array}\,\bef\,\begin{array}{||cc|}
\text{id} & \bbnum 0\\
\bbnum 0 & \overline{\psi}^{\uparrow M\uparrow F}\bef\phi^{\uparrow F}
\end{array}\,\bef\text{pu}_{M^{\prime}}\\
 & =\overline{\text{sw}}_{M,L}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef\,\gunderline{\begin{array}{||cc|}
\bbnum 0 & \overline{\psi}^{\uparrow M\uparrow F}\bef\phi^{\uparrow F}\end{array}}\,\bef\text{pu}_{M^{\prime}}\\
 & =\overline{\text{sw}}_{M,L}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef\gunderline{\overline{\psi}^{\uparrow M\uparrow F}\bef\phi^{\uparrow F}\bef(p\rightarrow\bbnum 0+p)}\bef\text{pu}_{M^{\prime}}\quad.
\end{align*}
The remaining difference in Eq.~(\ref{eq:monadic-naturality-swap-free-monad-derivation1})
is
\[
\overline{\text{sw}}_{M,L}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef\overline{\psi}^{\uparrow M\uparrow F}\bef\phi^{\uparrow F}\overset{?}{=}\big(\phi^{\overline{\uparrow L}}\big)^{\uparrow M\uparrow F}\bef\overline{\psi}^{\uparrow M\uparrow F}\bef\phi^{\uparrow F}\bef\overline{\text{sw}}_{M^{\prime},L^{\prime}}^{\uparrow M^{\prime}\uparrow F}\bef\text{ftn}_{M^{\prime}}^{\uparrow F}\quad,
\]
which we can simplify by omitting the common lifting $^{\uparrow F}$:
\begin{equation}
\overline{\text{sw}}_{M,L}^{\uparrow M}\bef\text{ftn}_{M}\bef\overline{\psi}^{\uparrow M}\bef\phi\overset{?}{=}\big(\phi^{\overline{\uparrow L}}\big)^{\uparrow M}\bef\overline{\psi}^{\uparrow M}\bef\phi\bef\overline{\text{sw}}_{M^{\prime},L^{\prime}}^{\uparrow M^{\prime}}\bef\text{ftn}_{M^{\prime}}\quad.\label{eq:monadic-naturality-swap-free-monad-derivation2}
\end{equation}
To transform the right-hand side of Eq.~(\ref{eq:monadic-naturality-swap-free-monad-derivation2}),
we need the inductive assumption that Eq.~(\ref{eq:monadic-naturality-swap-free-monad})
already holds for $\overline{\text{sw}}$. To use that assumption,
we need to move $\overline{\text{sw}}$ next to $\phi^{\uparrow L}\bef\psi$
under $^{\uparrow M}$:
\begin{align*}
 & \big(\phi^{\overline{\uparrow L}}\big)^{\uparrow M}\bef\overline{\psi}^{\uparrow M}\bef\gunderline{\phi\bef\overline{\text{sw}}_{M^{\prime},L^{\prime}}^{\uparrow M^{\prime}}}\bef\text{ftn}_{M^{\prime}}\\
{\color{greenunder}\text{naturality of }\phi:}\quad & =\big(\phi^{\overline{\uparrow L}}\bef\overline{\psi}\bef\text{\ensuremath{\overline{\text{sw}}_{M^{\prime},L^{\prime}}}}\big)^{\uparrow M}\bef\phi\bef\text{ftn}_{M^{\prime}}\\
{\color{greenunder}\text{inductive assumption, Eq.~(\ref{eq:monadic-naturality-swap-free-monad}) for }\overline{\text{sw}}:}\quad & =\big(\text{sw}_{M,L}\bef\psi^{\uparrow M}\bef\gunderline{\phi\big)^{\uparrow M}\bef\phi\bef\text{ftn}_{M^{\prime}}}\\
{\color{greenunder}\text{composition law of }\phi:}\quad & =\text{sw}_{M,L}^{\uparrow M}\bef\gunderline{\psi^{\uparrow M\uparrow M}\bef\text{ftn}_{M}}\bef\phi\\
{\color{greenunder}\text{naturality of }\text{ftn}_{M}:}\quad & =\text{sw}_{M,L}^{\uparrow M}\bef\text{ftn}_{M}\bef\psi^{\uparrow M}\bef\phi\quad.
\end{align*}
The two sides of Eq.~(\ref{eq:monadic-naturality-swap-free-monad-derivation2})
are now equal, which completes the proof of the law.

\paragraph{Runner laws}

To show that $\text{frun}^{M,M^{\prime}}(\phi)$ is a monad morphism
$T\leadsto T^{\prime}$, first check the identity law:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{pu}_{T^{\prime}}:}\quad & \text{pu}_{T}\bef\text{frun}^{M,M^{\prime}}(\phi)=\text{pu}_{L}\bef\gunderline{\text{pu}_{M}\bef\psi^{\uparrow M}}\bef\phi\\
{\color{greenunder}\text{naturality of }\text{pu}_{M}:}\quad & =\gunderline{\text{pu}_{L}\bef\psi}\bef\gunderline{\text{pu}_{M}\bef\phi}\\
{\color{greenunder}\text{identity laws of }\phi,\psi:}\quad & =\text{pu}_{L^{\prime}}\bef\text{pu}_{M^{\prime}}=\text{pu}_{T^{\prime}}\quad.
\end{align*}

To check the composition law, write the two sides separately:
\begin{align*}
{\color{greenunder}\text{left-hand side}:}\quad & \text{ftn}_{T}\bef\text{frun}\,(\phi)=\text{sw}^{\uparrow M}\bef\text{ftn}_{M}\bef\text{ftn}_{L}^{\uparrow M}\bef\psi^{\uparrow M}\bef\phi\quad,\\
{\color{greenunder}\text{right-hand side}:}\quad & (\text{frun}\,(\phi))^{\uparrow T}\bef\text{frun}\,(\phi)\bef\text{ftn}_{T^{\prime}}=(\psi^{\uparrow M}\bef\phi)^{\uparrow L\uparrow M}\bef\psi^{\uparrow M}\bef\phi\bef\text{sw}_{M^{\prime},L^{\prime}}^{\uparrow M^{\prime}}\bef\text{ftn}_{M^{\prime}}\bef\text{ftn}_{L^{\prime}}^{\uparrow M^{\prime}}\quad.
\end{align*}
We begin with the right-hand side since it is more complicated. In
order to show that it is equal to the left-hand side, we need somehow
to move \lstinline!swap! to the left in the function compositions,
so that we may use Eq.~(\ref{eq:monadic-naturality-swap-free-monad}):
\begin{align*}
{\color{greenunder}\text{right-hand side}:}\quad & (\psi^{\uparrow M}\bef\phi)^{\uparrow L\uparrow M}\bef\psi^{\uparrow M}\bef\gunderline{\phi\bef\text{sw}_{M^{\prime},L^{\prime}}^{\uparrow M^{\prime}}}\bef\text{ftn}_{M^{\prime}}\bef\text{ftn}_{L^{\prime}}^{\uparrow M^{\prime}}\\
{\color{greenunder}\text{naturality of }\phi:}\quad & =\big((\psi^{\uparrow M}\bef\gunderline{\phi)^{\uparrow L}\bef\psi\bef\text{sw}_{M^{\prime},L^{\prime}}}\big)^{\uparrow M}\bef\phi\bef\text{ftn}_{M^{\prime}}\bef\text{ftn}_{L^{\prime}}^{\uparrow M^{\prime}}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:monadic-naturality-swap-free-monad}) under }^{\uparrow M}:}\quad & =\big(\gunderline{\psi^{\uparrow M\uparrow L}\bef\text{sw}_{M,L}}\bef\psi^{\uparrow M}\bef\gunderline{\phi\big)^{\uparrow M}\bef\phi\bef\text{ftn}_{M^{\prime}}}\bef\text{ftn}_{L^{\prime}}^{\uparrow M^{\prime}}\\
{\color{greenunder}\text{composition law of }\phi:}\quad & =\text{sw}_{M,L}\bef\gunderline{\big(\psi^{\uparrow L}\bef\psi\big)^{\uparrow M\uparrow M}\bef\text{ftn}_{M}}\bef\gunderline{\phi\bef\text{ftn}_{L^{\prime}}^{\uparrow M^{\prime}}}\\
{\color{greenunder}\text{naturality of }\text{ftn}_{M}\text{ and }\phi:}\quad & =\text{sw}_{M,L}\bef\text{ftn}_{M}\bef\gunderline{\big(\psi^{\uparrow L}\bef\psi\big)^{\uparrow M}\bef\text{ftn}_{L^{\prime}}^{\uparrow M}}\bef\phi\\
{\color{greenunder}\text{composition law of }\psi:}\quad & =\text{sw}_{M,L}\bef\text{ftn}_{M}\bef\big(\text{ftn}_{L}\bef\psi\big)^{\uparrow M}\bef\phi\quad.
\end{align*}
The last line equals the left-hand side of the law.

\paragraph{Functor laws of \texttt{frun}}

To verify the functor laws of $\text{frun}$, begin with the identity
law. If $\phi=\text{id}$, Equation~(\ref{eq:free-monad-definition-of-psi})
defines the corresponding function $\psi$ also as $\psi=\text{id}$,
and so the identity law holds:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{id}:}\quad & \text{frun}\,(\text{id})=\psi^{\uparrow M}\bef\phi=\text{id}^{\uparrow M}\bef\text{id}=\text{id}\quad.
\end{align*}
To verify the composition law, take any monad morphisms $\phi_{1}:Q\leadsto R$
and $\phi_{2}:R\leadsto S$, where $Q$, $R$, $S$ are some foreign
monads. Denote temporarily $L_{Q}\triangleq\text{Free}^{F\circ Q}$,
$L_{R}\triangleq\text{Free}^{F\circ R}$, $L_{S}\triangleq\text{Free}^{F\circ S}$.
Then denote the corresponding monad morphisms by $\psi_{1}:L_{Q}\leadsto L_{R}$
and $\psi_{2}:L_{R}\leadsto L_{S}$ and write:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{frun}\,(\phi_{1}\bef\phi_{2}):}\quad & \text{frun}\,(\phi_{1})\bef\text{frun}(\phi_{2})=\psi_{1}^{\uparrow Q}\bef\gunderline{\phi_{1}\bef\psi_{2}^{\uparrow R}}\bef\phi_{2}\\
{\color{greenunder}\text{naturality of }\phi_{1}:}\quad & =\psi_{1}^{\uparrow Q}\bef\psi_{2}^{\uparrow Q}\bef\phi_{1}\bef\phi_{2}=(\psi_{1}\bef\psi_{2})^{\uparrow Q}\bef(\phi_{1}\bef\phi_{2})\quad.
\end{align*}
It remains to show that $\psi_{1}\bef\psi_{2}$ is the monad morphism
$L_{Q}\leadsto L_{S}$ corresponding to the composition $\phi_{1}\bef\phi_{2}$.
By Eq.~(\ref{eq:free-monad-definition-of-psi}), we have:
\begin{align*}
 & \psi_{1}\bef\psi_{2}=\,\begin{array}{|c||cc|}
 & A & (F\circ R\circ L_{R})^{A}\\
\hline A & \text{id} & \bbnum 0\\
(F\circ Q\circ L_{Q})^{A} & \bbnum 0 & \overline{\psi}_{1}^{\uparrow Q\uparrow F}\bef\phi_{1}^{\uparrow F}
\end{array}\,\bef\,\begin{array}{|c||cc|}
 & A & (F\circ S\circ L_{S})^{A}\\
\hline A & \text{id} & \bbnum 0\\
(F\circ R\circ L_{R})^{A} & \bbnum 0 & \overline{\psi}_{2}^{\uparrow R\uparrow F}\bef\phi_{2}^{\uparrow F}
\end{array}\\
 & =\,\begin{array}{|c||cc|}
 & A & (F\circ S\circ L_{S})^{A}\\
\hline A & \text{id} & \bbnum 0\\
(F\circ Q\circ L_{Q})^{A} & \bbnum 0 & \overline{\psi}_{1}^{\uparrow Q\uparrow F}\bef\phi_{1}^{\uparrow F}\bef\overline{\psi}_{2}^{\uparrow R\uparrow F}\bef\phi_{2}^{\uparrow F}
\end{array}\quad.
\end{align*}
We need to show that this equals the code matrix given by Eq.~(\ref{eq:free-monad-definition-of-psi})
for $\phi_{1}\bef\phi_{2}$:
\[
\psi_{1}\bef\psi_{2}\overset{?}{=}\psi\triangleq\,\begin{array}{|c||cc|}
 & A & (F\circ S\circ L_{S})^{A}\\
\hline A & \text{id} & \bbnum 0\\
(F\circ Q\circ L_{Q})^{A} & \bbnum 0 & \overline{\psi}^{\uparrow Q\uparrow F}\bef(\phi_{1}\bef\phi_{2})^{\uparrow F}
\end{array}\quad.
\]
Since $\psi$ is a recursive function, we may use the inductive assumption
that $\overline{\psi}=\overline{\psi}_{1}\bef\overline{\psi}_{2}$
for the recursive calls. The difference between the matrices is then
reduced to
\[
\overline{\psi}_{1}^{\uparrow Q\uparrow F}\bef\phi_{1}^{\uparrow F}\bef\overline{\psi}_{2}^{\uparrow R\uparrow F}\bef\phi_{2}^{\uparrow F}\overset{?}{=}(\psi_{1}\bef\psi_{2})^{\uparrow Q\uparrow F}\bef(\phi_{1}\bef\phi_{2})^{\uparrow F}\quad.
\]
The last equality holds since $\phi_{1}\bef\overline{\psi}_{2}^{\uparrow R}=\overline{\psi}_{2}^{\uparrow Q}\bef\phi_{1}$
due to naturality of $\phi_{1}$. This proves the law.

\paragraph{Base runner laws}

The base runner needs to satisfy the monad morphism laws and the non-degeneracy
law. Let us temporarily denote by $K$ the base monad, $K\triangleq\text{Free}^{F}$,
and by $\xi$ the function
\[
\xi:L^{A}\rightarrow K^{M^{A}}\quad,\quad\quad\xi\triangleq\,\begin{array}{|c||cc|}
 & M^{A} & F^{K^{M^{A}}}\\
\hline A & \text{pu}_{M} & \bbnum 0\\
F^{M^{L^{A}}} & \bbnum 0 & (\overline{\text{brun}}\,(\theta)\bef(x^{:M^{A}}\rightarrow x+\bbnum 0^{:F^{K^{M^{A}}}}))^{\uparrow F}
\end{array}\quad.
\]
We can then write the code for $\text{brun}\,(\theta)$ more conveniently:
\[
\text{brun}\,(\theta)\triangleq\xi^{\uparrow M}\bef\theta^{\uparrow M}\bef\text{ftn}_{M}\quad.
\]
To show that $\text{brun}\,(\theta)$ is a monad morphism, we will
use Statement~\ref{subsec:Statement-monad-morphism-composition-theorem}
with the monads $M$, $L$ instead of $M$, $N$. The required monad
morphism $\phi:L\leadsto M$ is defined as $\phi\triangleq\xi\bef\theta$.
It remains to verify that $\phi$ is indeed a monad morphism and that
\lstinline!swap! satisfies the special law with respect to $\phi$.

Although $\theta:K\leadsto\text{Id}$ is an arbitrary runner, its
behavior is constrained by the laws of monad morphisms. To extract
some useful information about $\theta$, begin with its identity law:
\[
\text{pu}_{K}\bef\theta=\text{id}\quad,\quad\quad\text{or equivalently:}\quad\quad(x\rightarrow x+\bbnum 0)\bef\theta=\text{id}\quad.
\]
If we apply $\theta$ to a value of type $\bbnum 0+F^{A+\bbnum 0}$,
the result must be of type $A$. Since the type $\bbnum 0+F^{A+\bbnum 0}$
is equivalent to $F^{A}$, we have obtained a transformation $r:F^{A}\rightarrow A$
that extracts values from $F$-wrappers. We can write this property
as a definition of the function $r$ through $\theta$:
\[
r:F^{A}\rightarrow A\quad,\quad\quad r\triangleq(x^{:A}\rightarrow x+\bbnum 0^{:F^{K^{A}}})^{\uparrow F}\bef(y^{:F^{A+\bbnum 0}}\rightarrow\bbnum 0^{:A}+y)\bef\theta\quad.
\]
Since $\theta$ is a natural transformation (because it is a monad
morphism), $r$ is also a natural transformation. In the rest of this
derivation, we will only need to use the naturality property of $r$;
we will not need to know the code of $r$.

With these equations, we can simplify the function $\phi\triangleq\xi\bef\theta$
by first rewriting the definition of $\phi$ in a way that does not
explicitly depend on $\text{brun}\,(\theta)$. Since $\text{brun}\,(\theta)=\phi^{\uparrow M}\bef\text{ftn}_{M}$,
we have:
\[
\phi\triangleq\xi\bef\theta=\,\begin{array}{|c||cc|}
 & M^{A} & F^{K^{M^{A}}}\\
\hline A & \text{pu}_{M} & \bbnum 0\\
F^{M^{L^{A}}} & \bbnum 0 & (\overline{\phi}^{\uparrow M}\bef\text{ftn}_{M}\bef(x^{:M^{A}}\rightarrow x+\bbnum 0^{:F^{K^{M^{A}}}}))^{\uparrow F}
\end{array}\,\bef\theta\quad.
\]
 Now we may merge the matrix columns of $\xi$ and compute the composition
with $\theta$:
\begin{align}
 & \phi=\xi\bef\theta=\,\begin{array}{|c||c|}
 & M^{A}+F^{K^{M^{A}}}\\
\hline A & \text{pu}_{M}\bef(x\rightarrow x+\bbnum 0)\\
F^{M^{L^{A}}} & (\overline{\phi}^{\uparrow M}\bef\text{ftn}_{M}\bef(x\rightarrow x+\bbnum 0))^{\uparrow F}\bef(x\rightarrow\bbnum 0+x)
\end{array}\,\bef\theta\nonumber \\
 & =\,\begin{array}{|c||c|}
 & M^{A}\\
\hline A & \text{pu}_{M}\bef\gunderline{(x\rightarrow x+\bbnum 0)\bef\theta}\\
F^{M^{L^{A}}} & (\overline{\phi}^{\uparrow M}\bef\text{ftn}_{M}\bef\gunderline{(x\rightarrow x+\bbnum 0))^{\uparrow F}\bef(x\rightarrow\bbnum 0+x)\bef\theta}
\end{array}\,=\,\begin{array}{|c||c|}
 & M^{A}\\
\hline A & \text{pu}_{M}\\
F^{M^{L^{A}}} & \overline{\phi}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef r
\end{array}\quad.\label{eq:simplified-phi-free-monad-transformer-derivation1}
\end{align}

With the simplified code for $\phi$, we proceed with the proof. To
verify the identity law of $\phi$:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{pu}_{M}:}\quad & \text{pu}_{L}\bef\phi=\,\begin{array}{||cc|}
\text{id} & \bbnum 0\end{array}\,\bef\,\begin{array}{||c|}
\text{pu}_{M}\\
\overline{\phi}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef r
\end{array}=\text{pu}_{M}\quad.
\end{align*}

To verify the composition law of $\phi$, begin with the left-hand
side of that law:
\begin{align*}
{\color{greenunder}\text{left-hand side}:}\quad & \text{ftn}_{L}\bef\phi=\,\begin{array}{|c||cc|}
 & A & F^{M^{L^{A}}}\\
\hline A & \text{id} & \bbnum 0\\
F^{M^{L^{A}}} & \bbnum 0 & \text{id}\\
F^{M^{L^{L^{A}}}} & \bbnum 0 & \overline{\text{ftn}}_{L}^{\uparrow M\uparrow F}
\end{array}\,\bef\,\begin{array}{|c||c|}
 & M^{A}\\
\hline A & \text{pu}_{M}\\
F^{M^{L^{A}}} & \overline{\phi}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef r
\end{array}\\
 & =\,\begin{array}{|c||c|}
 & M^{A}\\
\hline A & \text{pu}_{M}\\
F^{M^{L^{A}}} & \overline{\phi}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef r\\
F^{M^{L^{L^{A}}}} & \overline{\text{ftn}}_{L}^{\uparrow M\uparrow F}\bef\overline{\phi}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef r
\end{array}\quad.
\end{align*}
It is easier to work with the right-hand side of the law if we first
simplify the function $\phi\bef\text{ftn}_{M}$: 
\begin{align*}
 & \phi\bef\text{ftn}_{M}=\,\begin{array}{|c||c|}
 & M^{M^{A}}\\
\hline M^{A} & \text{pu}_{M}\\
F^{M^{L^{M^{A}}}} & \overline{\phi}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef r
\end{array}\,\bef\text{ftn}_{M}=\,\begin{array}{|c||c|}
 & M^{A}\\
\hline M^{A} & \gunderline{\text{pu}_{M}\bef\text{ftn}_{M}}\\
F^{M^{L^{M^{A}}}} & \overline{\phi}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef\gunderline{r\bef\text{ftn}_{M}}
\end{array}\quad.\\
 & =\,\begin{array}{|c||c|}
 & M^{A}\\
\hline M^{A} & \text{id}\\
F^{M^{L^{M^{A}}}} & \big(\overline{\phi}^{\uparrow M}\bef\text{ftn}_{M}\bef\text{ftn}_{M}\big)^{\uparrow F}\bef r
\end{array}\quad.
\end{align*}
Now we write the right-hand side of the composition law:
\begin{align*}
{\color{greenunder}\text{right-hand side}:}\quad & \phi^{\uparrow L}\bef\phi\bef\text{ftn}_{M}\\
 & \quad=\,\begin{array}{|c||cc|}
 & M^{A} & F^{M^{L^{M^{A}}}}\\
\hline A & \text{pu}_{M} & \bbnum 0\\
F^{M^{L^{A}}} & \overline{\phi}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef r & \bbnum 0\\
F^{M^{L^{L^{A}}}} & \bbnum 0 & \overline{\phi}^{\uparrow L\uparrow M\uparrow F}
\end{array}\,\bef\,\begin{array}{|c||c|}
 & M^{A}\\
\hline M^{A} & \text{id}\\
F^{M^{L^{M^{A}}}} & \big(\overline{\phi}^{\uparrow M}\bef\text{ftn}_{M}\bef\text{ftn}_{M}\big)^{\uparrow F}\bef r
\end{array}\\
 & \quad=\,\,\begin{array}{|c||c|}
 & M^{A}\\
\hline A & \text{pu}_{M}\\
F^{M^{L^{A}}} & \overline{\phi}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef r\\
F^{M^{L^{L^{A}}}} & \big(\overline{\phi}^{\uparrow L\uparrow M}\bef\overline{\phi}^{\uparrow M}\bef\text{ftn}_{M}\bef\text{ftn}_{M}\big)^{\uparrow F}\bef r
\end{array}\quad.
\end{align*}
The remaining difference is in the last rows of the matrices:
\[
\big(\overline{\text{ftn}}_{L}^{\uparrow M}\bef\overline{\phi}^{\uparrow M}\bef\text{ftn}_{M}\big)^{\uparrow F}\bef r\overset{?}{=}\big(\overline{\phi}^{\uparrow L\uparrow M}\bef\overline{\phi}^{\uparrow M}\bef\text{ftn}_{M}\bef\text{ftn}_{M}\big)^{\uparrow F}\bef r\quad.
\]
We will prove this equality if we show that
\[
\overline{\text{ftn}}_{L}^{\uparrow M}\bef\overline{\phi}^{\uparrow M}\bef\text{ftn}_{M}\overset{?}{=}\overline{\phi}^{\uparrow L\uparrow M}\bef\overline{\phi}^{\uparrow M}\bef\text{ftn}_{M}\bef\text{ftn}_{M}\quad.
\]
Substitute the inductive assumption for the recursive calls to $\overline{\phi}$:
\[
\text{ftn}_{L}\bef\overline{\phi}=\overline{\phi}^{\uparrow L}\bef\overline{\phi}\bef\text{ftn}_{M}\quad.
\]
Then we only need to show the following equality:
\begin{align*}
 & \gunderline{\overline{\text{ftn}}_{L}^{\uparrow M}\bef\overline{\phi}^{\uparrow M}}\bef\text{ftn}_{M}=\big(\overline{\phi}^{\uparrow L}\bef\overline{\phi}\bef\text{ftn}_{M}\big)^{\uparrow M}\bef\text{ftn}_{M}\\
 & \overset{?}{=}\overline{\phi}^{\uparrow L\uparrow M}\bef\overline{\phi}^{\uparrow M}\bef\gunderline{\text{ftn}_{M}\bef\text{ftn}_{M}}=\overline{\phi}^{\uparrow L\uparrow M}\bef\overline{\phi}^{\uparrow M}\bef\text{ftn}_{M}^{\uparrow M}\bef\text{ftn}_{M}\quad.
\end{align*}
The last expressions are now equal, which completes the derivation.

It remains to check the special law of \lstinline!swap!:
\begin{equation}
\text{sw}\bef\phi^{\uparrow M}\bef\text{ftn}_{M}\overset{?}{=}\phi\bef\text{ftn}_{M}\quad.\label{eq:free-monad-transformer-swap-law-derivation2}
\end{equation}
Substitute the code of \lstinline!swap! from Eq.~(\ref{eq:definition-of-swap-for-free-monad-transformer})
into the left-hand side:
\begin{align*}
 & \text{sw}\bef\phi^{\uparrow M}\bef\text{ftn}_{M}=\,\begin{array}{|c||c|}
 & M^{A}\\
\hline M^{A} & \gunderline{\text{pu}_{L}^{\uparrow M}\bef\phi^{\uparrow M}}\bef\text{ftn}_{M}\\
F^{M^{L^{M^{A}}}} & \overline{\text{sw}}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0^{:A}+p)\bef\gunderline{\text{pu}_{M}\bef\phi^{\uparrow M}}\bef\text{ftn}_{M}
\end{array}\\
 & =\,\begin{array}{|c||c|}
 & M^{A}\\
\hline M^{A} & \gunderline{\text{pu}_{M}^{\uparrow M}\bef\text{ftn}_{M}}\\
F^{M^{L^{M^{A}}}} & \overline{\text{sw}}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0^{:A}+p)\bef\phi\bef\gunderline{\text{pu}_{M}\bef\text{ftn}_{M}}
\end{array}\\
 & =\,\,\begin{array}{|c||c|}
 & M^{A}\\
\hline M^{A} & \text{id}\\
F^{M^{L^{M^{A}}}} & \overline{\text{sw}}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0^{:A}+p)\bef\phi
\end{array}\quad.
\end{align*}
We can further simplify the last matrix row if we substitute the code
for $\phi$ from Eq.~(\ref{eq:simplified-phi-free-monad-transformer-derivation1}):
\begin{align*}
 & \overline{\text{sw}}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef(p\rightarrow\bbnum 0^{:A}+p)\bef\phi\\
 & =\overline{\text{sw}}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef\,\begin{array}{||cc|}
\bbnum 0 & \text{id}\end{array}\,\bef\,\begin{array}{|c||c|}
 & M^{A}\\
\hline A & \text{pu}_{M}\\
F^{M^{L^{A}}} & \overline{\phi}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef r
\end{array}\\
 & =\overline{\text{sw}}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef\overline{\phi}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef r=\big(\overline{\text{sw}}^{\uparrow M}\bef\gunderline{\text{ftn}_{M}\bef\overline{\phi}^{\uparrow M}}\bef\text{ftn}_{M}\big)^{\uparrow F}\bef r\\
 & =\big(\overline{\text{sw}}^{\uparrow M}\bef\phi^{\uparrow M\uparrow M}\bef\gunderline{\text{ftn}_{M}\bef\text{ftn}_{M}}\big)^{\uparrow F}\bef r=\big(\gunderline{\overline{\text{sw}}^{\uparrow M}\bef\phi^{\uparrow M\uparrow M}\bef\text{ftn}_{M}^{\uparrow M}}\bef\text{ftn}_{M}\big)^{\uparrow F}\bef r\\
{\color{greenunder}\text{inductive assumption}:}\quad & \big((\overline{\phi}\bef\gunderline{\text{ftn}_{M})^{\uparrow M}\bef\text{ftn}_{M}}\big)^{\uparrow F}\bef r=\big(\overline{\phi}^{\uparrow M}\bef\text{ftn}_{M}\bef\text{ftn}_{M}\big)^{\uparrow F}\bef r\quad.
\end{align*}
Now substitute Eq.~(\ref{eq:simplified-phi-free-monad-transformer-derivation1})
into the right-hand side of Eq.~(\ref{eq:free-monad-transformer-swap-law-derivation2}):
\[
\phi\bef\text{ftn}_{M}=\,\begin{array}{|c||c|}
 & M^{M^{A}}\\
\hline M^{A} & \text{pu}_{M}\\
F^{M^{L^{M^{A}}}} & \overline{\phi}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef r
\end{array}\,\bef\text{ftn}_{M}=\,\begin{array}{|c||c|}
 & M^{A}\\
\hline M^{A} & \text{pu}_{M}\bef\text{ftn}_{M}\\
F^{M^{L^{M^{A}}}} & \overline{\phi}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef r\bef\text{ftn}_{M}
\end{array}\quad.
\]
The difference between the two sides of Eq.~(\ref{eq:free-monad-transformer-swap-law-derivation2})
is now reduced to
\[
(\overline{\phi}^{\uparrow M}\bef\text{ftn}_{M}\bef\gunderline{\text{ftn}_{M})^{\uparrow F}\bef r}\overset{?}{=}\overline{\phi}^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef\gunderline{r\bef\text{ftn}_{M}}\quad.
\]
This holds due to naturality of $r:F\leadsto\text{Id}$, which proves
Eq.~(\ref{eq:free-monad-transformer-swap-law-derivation2}).

The requirements of Statement~\ref{subsec:Statement-monad-morphism-composition-theorem}
are now satisfied, so $\text{brun}\,(\theta)$ is a monad morphism.

The non-degeneracy law of \lstinline!brun! is an equation between
functions of type $M^{A}\rightarrow M^{A}$:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{id}:}\quad & \text{flift}\bef\text{brun}\,(\theta)=\text{pu}_{L}^{\uparrow M}\bef\text{brun}\,(\theta)=\text{pu}_{L}^{\uparrow M}\bef\gunderline{\xi^{\uparrow M}\bef\theta^{\uparrow M}}\bef\text{ftn}_{M}=(\gunderline{\text{pu}_{L}\bef\phi})^{\uparrow M}\bef\text{ftn}_{M}\\
{\color{greenunder}\text{identity law of }\phi:}\quad & =\text{pu}_{M}^{\uparrow M}\bef\text{ftn}_{M}=\text{id}\quad.
\end{align*}


\paragraph{Monadic naturality laws}

The monadic naturality law of \lstinline!flift! is 
\begin{align*}
 & \text{flift}\bef\text{frun}\,(\phi)\overset{?}{=}\phi\bef\text{flift}\quad,\\
{\color{greenunder}\text{or, using definitions of }\text{flift}\text{ and }\text{frun}:}\quad & \text{pu}_{L}^{\uparrow M}\bef\psi^{\uparrow M}\bef\phi\overset{?}{=}\phi\bef\text{pu}_{L^{\prime}}^{\uparrow M^{\prime}}\quad,
\end{align*}
which should hold for any natural transformation $\phi^{:M\leadsto M^{\prime}}$.
Here, we denoted $L^{\prime}\triangleq\text{Free}^{F\circ M^{\prime}}$.
Since $\psi:L\leadsto L^{\prime}$ is a monad morphism, we find
\begin{align*}
{\color{greenunder}\text{expect to equal }\phi\bef\text{pu}_{L^{\prime}}^{\uparrow M^{\prime}}:}\quad & \text{pu}_{L}^{\uparrow M}\bef\psi^{\uparrow M}\bef\phi=(\text{pu}_{L}\bef\psi)^{\uparrow M}\bef\phi=\phi\bef\big(\gunderline{\text{pu}_{L}\bef\psi}\big)^{\uparrow M^{\prime}}=\phi\bef\text{pu}_{L^{\prime}}^{\uparrow M^{\prime}}\quad.
\end{align*}

The monadic naturality law of $\text{brun}_{L}$ is
\[
\text{brun}_{L}(\theta)\bef\phi\overset{?}{=}\text{frun}\,(\phi)\bef\text{brun}_{L^{\prime}}(\theta)\quad.
\]
This law should hold for any monad morphism $\phi:M\leadsto M^{\prime}$.
Write the two sides separately:
\begin{align*}
{\color{greenunder}\text{left-hand side}:}\quad & \text{brun}_{L}(\theta)\bef\phi=\xi^{\uparrow M}\bef\theta^{\uparrow M}\bef\gunderline{\text{ftn}_{M}\bef\phi}\\
{\color{greenunder}\text{composition law of }\phi:}\quad & \quad=\gunderline{\xi^{\uparrow M}\bef\theta^{\uparrow M}\bef\phi^{\uparrow M}}\bef\phi\bef\text{ftn}_{M^{\prime}}=(\xi\bef\theta\bef\phi)^{\uparrow M}\bef\phi\bef\text{ftn}_{M^{\prime}}\quad,\\
{\color{greenunder}\text{right-hand side}:}\quad & \text{frun}\,(\phi)\bef\text{brun}_{L^{\prime}}(\theta)=\psi^{\uparrow M}\bef\gunderline{\phi\bef\xi^{\uparrow M^{\prime}}\bef\theta^{\uparrow M^{\prime}}}\bef\text{ftn}_{M^{\prime}}\\
{\color{greenunder}\text{naturality of }\phi:}\quad & \quad=(\psi\bef\xi\bef\theta)^{\uparrow M}\bef\phi\bef\text{ftn}_{M}\quad.
\end{align*}
The remaining difference is a comparison of functions of type $L^{A}\rightarrow M^{\prime A}$:
\begin{equation}
\xi\bef\theta\bef\phi\overset{?}{=}\psi\bef\xi\bef\theta\quad.\label{eq:monadic-naturality-free-monad-transformer-derivation1}
\end{equation}
Substituting Eq.~(\ref{eq:free-monad-definition-of-psi}) instead
of $\psi$ and Eq.~(\ref{eq:simplified-phi-free-monad-transformer-derivation1})
instead of $\xi\bef\theta$, we transform this equality to
\begin{align*}
 & \begin{array}{||c|}
\text{pu}_{M}\\
\overline{\xi}^{\uparrow M\uparrow F}\bef\theta^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef r
\end{array}\,\bef\phi=\,\begin{array}{||c|}
\gunderline{\text{pu}_{M}\bef\phi}\\
\overline{\xi}^{\uparrow M\uparrow F}\bef\theta^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef r\bef\phi
\end{array}\,=\,\begin{array}{||c|}
\text{pu}_{M^{\prime}}\\
\overline{\xi}^{\uparrow M\uparrow F}\bef\theta^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef r\bef\phi
\end{array}\\
 & \overset{?}{=}\,\begin{array}{||cc|}
\text{id} & \bbnum 0\\
\bbnum 0 & \overline{\psi}^{\uparrow M\uparrow F}\bef\phi^{\uparrow F}
\end{array}\bef\,\begin{array}{||c|}
\text{pu}_{M^{\prime}}\\
\overline{\xi}^{\uparrow M^{\prime}\uparrow F}\bef\theta^{\uparrow M^{\prime}\uparrow F}\bef\text{ftn}_{M^{\prime}}^{\uparrow F}\bef r
\end{array}\,=\,\begin{array}{||c|}
\text{pu}_{M^{\prime}}\\
\overline{\psi}^{\uparrow M\uparrow F}\bef\phi^{\uparrow F}\bef\overline{\xi}^{\uparrow M^{\prime}\uparrow F}\bef\theta^{\uparrow M^{\prime}\uparrow F}\bef\text{ftn}_{M^{\prime}}^{\uparrow F}\bef r
\end{array}\quad.
\end{align*}
The remaining difference is
\[
\overline{\xi}^{\uparrow M\uparrow F}\bef\theta^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef r\bef\phi\overset{?}{=}\overline{\psi}^{\uparrow M\uparrow F}\bef\phi^{\uparrow F}\bef\overline{\xi}^{\uparrow M^{\prime}\uparrow F}\bef\theta^{\uparrow M^{\prime}\uparrow F}\bef\text{ftn}_{M^{\prime}}^{\uparrow F}\bef r\quad.
\]
By the inductive assumption, Eq.~(\ref{eq:monadic-naturality-free-monad-transformer-derivation1})
holds for recursive calls $\overline{\xi}$ and $\overline{\psi}$.
To use that assumption, we need to move these functions towards each
other in the compositions above:
\begin{align*}
 & \overline{\xi}^{\uparrow M\uparrow F}\bef\theta^{\uparrow M\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}\bef\gunderline{r\bef\phi}=\overline{\xi}^{\uparrow M\uparrow F}\bef\theta^{\uparrow M\uparrow F}\bef\gunderline{\text{ftn}_{M}^{\uparrow F}\bef\phi^{\uparrow F}}\bef r\\
{\color{greenunder}\text{composition law of }\phi:}\quad & =\gunderline{\overline{\xi}^{\uparrow M\uparrow F}\bef\theta^{\uparrow M\uparrow F}\bef\big(\phi^{\uparrow M}}\bef\phi\bef\text{ftn}_{M^{\prime}}\big)^{\uparrow F}\bef r=(\gunderline{\overline{\xi}\bef\theta\bef\phi})^{\uparrow M\uparrow F}\bef\phi^{\uparrow F}\bef\text{ftn}_{M^{\prime}}^{\uparrow F}\bef r\\
{\color{greenunder}\text{inductive assumption}:}\quad & =\big((\overline{\psi}\bef\gunderline{\xi\bef\theta)^{\uparrow M}\bef\phi}\bef\text{ftn}_{M^{\prime}}\big)^{\uparrow F}\bef r=\big((\overline{\psi}^{\uparrow M}\bef\phi\bef(\xi\bef\theta)^{\uparrow M^{\prime}}\bef\text{ftn}_{M^{\prime}}\big)^{\uparrow F}\bef r\quad.
\end{align*}
The two sides are now equal.

This concludes the proofs of the laws for the free monad transformer.

\subsection{Transformer for the \texttt{List} monad. Proofs}

The \lstinline!List! monad\textsf{'}s transformer, usually named \lstinline!ListT!,
is defined as a recursive type,
\[
T_{\text{List}}^{M,A}\triangleq M^{\bbnum 1+A\times T_{\text{List}}^{M,A}}\quad,
\]
that wraps each partial tail of the list into a separate layer of
an $M$-effect. The result is an \textsf{``}effectful list\textsf{''}: obtaining each
next element of the list requires running an $M$-effect. The \lstinline!flatten!
method ($\text{ftn}_{T}$) should sequence all $M$-effects of the
nested lists in the order they occur in the outer list.

Despite a superficial similarity between $T_{\text{List}}$ and the
transformers for the free monad and the free pointed monad, proofs
of the laws for $T_{\text{List}}$ require a different technique,
and the transformer\textsf{'}s implementation is significantly more complicated.
The reason is that the functor 
\[
L^{A}\triangleq\bbnum 1+A\times T_{\text{List}}^{M,A}=\bbnum 1+A\times M^{L^{A}}
\]
does not admit a monad instance that flattens the \textsf{``}effectful lists\textsf{''}
correctly (see Exercise~\ref{subsec:Exercise-effectful-list-not-monad}).
So, we cannot define $T_{\text{List}}=M\circ L$ as a functor composition
of two monads. As a result, the \lstinline!flatten! metnod of $T_{\text{List}}$,
which we will denote for brevity by $\text{ftn}_{T}$, cannot be defined
via a \lstinline!swap! function, as we have done for the other monad
transformers just mentioned. Instead, the \lstinline!flatten! method
of $T_{\text{List}}$ is defined via a special helper function named
\lstinline!prod! as shown in the following statement.\footnote{The function \lstinline!prod! was studied in the paper \textsf{``}Composing
monads\textsf{''} (\texttt{\href{http://web.cecs.pdx.edu/~mpj/pubs/RR-1004.pdf}{http://web.cecs.pdx.edu/$\sim$mpj/pubs/RR-1004.pdf}}).
However, that paper did not correctly define the \lstinline!List!
monad\textsf{'}s transformer.}

\subsubsection{Statement \label{subsec:Statement-list-monad-transformer}\ref{subsec:Statement-list-monad-transformer}}

The type constructor $T_{\text{List}}$ satisfies all the monad transformer
laws.

\subparagraph{Proof}

We will shortly implement a function called \lstinline!prod! with
the type signature
\[
\text{prod}:L^{M^{L^{A}}}\rightarrow M^{L^{A}}\cong\bbnum 1+M^{L^{A}}\times M^{L^{M^{L^{A}}}}\rightarrow M^{L^{A}}\quad.
\]
The monad methods of $T_{\text{List}}$ are then defined by

\begin{wrapfigure}{l}{0.4\columnwidth}%
\vspace{-1\baselineskip}

\[
\xymatrix{\xyScaleY{1.5pc}\xyScaleX{3.5pc}T^{T^{A}}=M^{L^{M^{L^{A}}}}\ar[r]\sp(0.6){\text{prod}^{\uparrow M}}\ar[rd]\sb(0.5){\text{ftn}_{T}\triangleq\ } & M^{M^{L^{A}}}\ar[d]\sp(0.45){\ \text{ftn}_{M}}\\
 & M^{L^{A}}
}
\]

\vspace{0\baselineskip}
\end{wrapfigure}%

~\vspace{-1.2\baselineskip}
\begin{equation}
\text{pu}_{T}\triangleq\text{pu}_{L}\bef\text{pu}_{M}\quad,\quad\quad\text{ftn}_{T}\triangleq\text{prod}^{\uparrow M}\bef\text{ftn}_{M}\quad.\label{eq:def-pure-flatten-via-prod-for-list-monad-transformer}
\end{equation}
The method $\text{pu}_{L}:A\rightarrow L^{A}$ creates a list with
a single element and an empty effect:
\[
\text{pu}_{L}\triangleq a^{:A}\rightarrow\bbnum 0^{:\bbnum 1}+a\times\text{pu}_{M}(1+\bbnum 0^{:A\times M^{L^{A}}})\quad.
\]
Since the value $1+\bbnum 0^{:A\times M^{L^{A}}}$ will be used frequently,
we denote it by $\text{Nil}^{:L^{A}}$. So, we write:
\[
\text{pu}_{L}\triangleq a^{:A}\rightarrow\bbnum 0^{:\bbnum 1}+a\times(\text{Nil}\triangleright\text{pu}_{M})=\,\begin{array}{|c||cc|}
 & \bbnum 1 & A\times M^{L^{A}}\\
\hline A & \bbnum 0 & a\rightarrow a\times\text{pu}_{M}(\text{Nil})
\end{array}\quad.
\]


\paragraph{Implementing \texttt{prod}}

The code of \lstinline!prod! uses a helper function that we temporarily
call \lstinline!comb!, with type
\[
\text{comb}:M^{L^{A}}\rightarrow M^{L^{A}}\rightarrow M^{L^{A}}\quad.
\]
This function \textsf{``}combines\textsf{''} two values of type $M^{L^{A}}\triangleq T_{\text{List}}^{A}$
into a new value of the same type:
\begin{equation}
\text{comb}\,(m)(n)\triangleq m\triangleright\text{flm}_{M}\bigg(\,\begin{array}{|c||c|}
 & M^{L^{A}}\\
\hline \bbnum 1 & 1\rightarrow n\\
A\times M^{L^{A}} & a\times p\rightarrow\text{pu}_{M}\big(\bbnum 0^{:\bbnum 1}+a\times\overline{\text{comb}}\,(p)(n)\big)
\end{array}\,\bigg)\quad.\label{eq:definition-of-comb-for-effectful-list}
\end{equation}
The code uses the monad $M$\textsf{'}s \lstinline!flatMap! method to sequence
all $M$-effects from the first list before all $M$-effects of the
second one. We will show in Statement~\ref{subsec:Statement-monoid-operation-comb-for-effectful-list}
that the \lstinline!comb! function is a monoidal operation for values
of type $T_{\text{List}}^{A}$; that property will be used in the
later derivations. The function \lstinline!prod! is defined recursively
via \lstinline!comb!:
\begin{equation}
\text{prod}\triangleq\,\begin{array}{|c||c|}
 & M^{L^{A}}\\
\hline \bbnum 1 & 1\rightarrow\text{Nil}\triangleright\text{pu}_{M}\\
M^{L^{A}}\times M^{L^{M^{L^{A}}}} & m\times p\rightarrow\text{comb}\,(m)(p\triangleright\overline{\text{prod}}^{\uparrow M}\bef\text{ftn}_{M})
\end{array}\quad.\label{eq:definition-of-prod-for-list-monad-transformer}
\end{equation}
The function \lstinline!prod! satisfies certain laws that we will
prove in Statement~\ref{subsec:Statement-laws-of-prod-for-effectful-list}
below. Besides a naturality law, \lstinline!prod! satisfies two identity
laws\index{identity laws!of prod for ListT@of \texttt{prod} for \texttt{ListT}}
and an \index{associativity law!of prod for ListT@of \texttt{prod} for \texttt{ListT}}associativity
law:
\begin{align}
{\color{greenunder}\text{identity laws}:}\quad & \text{pu}_{L}\bef\text{prod}=\text{id}\quad,\quad\quad\text{pu}_{T}^{\uparrow L}\bef\text{prod}=\text{pu}_{M}\quad,\label{eq:identity-laws-of-prod-for-effectful-list}\\
{\color{greenunder}\text{associativity law}:}\quad & \text{prod}\bef\text{prod}^{\uparrow M}\bef\text{ftn}_{M}=\text{prod}^{\uparrow M\uparrow L}\bef\text{ftn}_{M}^{\uparrow L}\bef\text{prod}\quad.\label{eq:associativity-law-of-prod-for-effectful-list}
\end{align}
\[
\xymatrix{\xyScaleY{1.5pc}\xyScaleX{3.0pc}M^{L^{A}}\ar[rd]\sp(0.5){\text{id}}\ar[d]\sb(0.45){\text{pu}_{L}} &  & L^{A}\ar[ld]\sb(0.5){\text{pu}_{M}}\ar[d]\sp(0.4){\text{pu}_{T}^{\uparrow L}} & L^{M^{L^{M^{L^{A}}}}}\ar[d]\sp(0.4){\text{prod}}\ar[r]\sp(0.55){\text{prod}^{\uparrow M\uparrow L}} & L^{M^{M^{L^{A}}}}\ar[r]\sp(0.5){\text{ftn}_{M}^{\uparrow L}} & L^{M^{L^{A}}}\ar[d]\sp(0.4){\text{prod}}\\
L^{M^{L^{A}}}\ar[r]\sp(0.45){\text{prod}} & M^{L^{A}} & \ar[l]\sb(0.45){\text{prod}}L^{M^{L^{A}}} & M^{L^{M^{L^{A}}}}\ar[r]\sp(0.5){\text{prod}^{\uparrow M}} & M^{M^{L^{A}}}\ar[r]\sp(0.55){\text{ftn}_{M}} & M^{L^{A}}
}
\]

We will now verify that these laws make the monad laws for $T_{\text{List}}$
hold automatically:

\paragraph{Monad laws}

of $T_{\text{List}}$ need to be verified using the monad methods
$\text{pu}_{T}$ and $\text{ftn}_{T}$ we defined above. The left
identity law of $T$:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{id}:}\quad & \text{pu}_{T}\bef\text{ftn}_{T}=\text{pu}_{L}\bef\gunderline{\text{pu}_{M}\bef\text{prod}^{\uparrow M}}\bef\text{ftn}_{M}=\gunderline{\text{pu}_{L}\bef\text{prod}}\bef\text{pu}_{M}\bef\text{ftn}_{M}\\
{\color{greenunder}\text{identity law of }\text{prod}:}\quad & =\text{pu}_{M}\bef\text{ftn}_{M}=\text{id}\quad.
\end{align*}
The right identity law of $T$:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{id}:}\quad & \text{pu}_{T}^{\uparrow T}\bef\text{ftn}_{T}=\gunderline{\text{pu}_{T}^{\uparrow L\uparrow M}\bef\text{prod}^{\uparrow M}}\bef\text{ftn}_{M}\\
{\color{greenunder}\text{identity law of }\text{prod}\text{ under }^{\uparrow M}:}\quad & =\gunderline{\text{pu}_{M}^{\uparrow M}\bef\text{ftn}_{M}}=\text{id}\quad.
\end{align*}

The associativity law of $T$:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{ftn}_{T}\bef\text{ftn}_{T}:}\quad & \text{ftn}_{T}^{\uparrow T}\bef\text{ftn}_{T}=\gunderline{(\text{prod}^{\uparrow M}\bef\text{ftn}_{M})^{\uparrow L\uparrow M}\bef\text{prod}^{\uparrow M}}\bef\text{ftn}_{M}\\
 & =(\gunderline{\text{prod}^{\uparrow M\uparrow L}\bef\text{ftn}_{M}^{\uparrow L}\bef\text{prod}})^{\uparrow M}\bef\text{ftn}_{M}\\
{\color{greenunder}\text{associativity law of }\text{prod}:}\quad & =(\text{prod}\bef\text{prod}^{\uparrow M}\bef\gunderline{\text{ftn}_{M})^{\uparrow M}\bef\text{ftn}_{M}}=\text{prod}^{\uparrow M}\bef\gunderline{\text{prod}^{\uparrow M\uparrow M}\bef\text{ftn}_{M}}\bef\text{ftn}_{M}\\
 & =\text{prod}^{\uparrow M}\bef\text{ftn}_{M}\bef\text{prod}^{\uparrow M}\bef\text{ftn}_{M}=\text{ftn}_{T}\bef\text{ftn}_{T}\quad.
\end{align*}


\paragraph{Identity laws}

When $M=\text{Id}$, the type constructor $T_{\text{List}}$ is equivalent
to \lstinline!List! since $T_{\text{List}}$ is then defined by the
recursive equation 
\[
T_{\text{List}}^{A}=M^{\bbnum 1+A\times T_{\text{List}}^{A}}\cong\bbnum 1+A\times T_{\text{List}}^{A}\quad.
\]
After setting $M=\text{Id}$, the code of $\text{pu}_{T}$, \lstinline!comb!,
and $\text{ftn}_{T}$ becomes the same as the code of $\text{pu}_{\text{List}}$,
\lstinline!concat! ($\pplus$), and $\text{ftn}_{\text{List}}$.
So, the identity laws hold for $T$.

\paragraph{Lifting laws}

The foreign lift function is implemented as
\[
\text{flift}:M^{A}\rightarrow M^{L^{A}}\quad,\quad\quad\text{flift}\triangleq\text{pu}_{L}^{\uparrow M}\quad.
\]
To show that \lstinline!flift! is a monad morphism, begin with the
identity law:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{pu}_{T}:}\quad & \text{pu}_{M}\bef\text{flift}=\gunderline{\text{pu}_{M}\bef\text{pu}_{L}^{\uparrow M}}=\text{pu}_{L}\bef\text{pu}_{M}\\
{\color{greenunder}\text{by definition of }\text{pu}_{T}:}\quad & =\text{pu}_{T}\quad.
\end{align*}
To verify the composition law, write its two sides separately:
\begin{align*}
{\color{greenunder}\text{left-hand side}:}\quad & \text{ftn}_{M}\bef\text{flift}=\text{ftn}_{M}\bef\text{pu}_{L}^{\uparrow M}\quad,\\
{\color{greenunder}\text{right-hand side}:}\quad & \text{flift}^{\uparrow M}\bef\text{flift}\bef\text{ftn}_{T}=\text{pu}_{L}^{\uparrow M\uparrow M}\bef\gunderline{\text{pu}_{L}^{\uparrow M}\bef\text{prod}^{\uparrow M}}\bef\text{ftn}_{M}\\
{\color{greenunder}\text{identity law of }\text{prod}:}\quad & \quad=\gunderline{\text{pu}_{L}^{\uparrow M\uparrow M}\bef\text{ftn}_{M}}=\text{ftn}_{M}\bef\text{pu}_{L}^{\uparrow M}\quad.
\end{align*}


\paragraph{Implementation of \texttt{frun}}

Since the transformer $T_{\text{List}}=M\circ L$ is not purely compositional
($L$ itself depends on $M$), mapping the monad $M$ to $M^{\prime}$
via a monad morphism $\phi:M\leadsto M^{\prime}$ requires us also
to map $L$ to $L^{\prime}$, where we define 
\[
L^{\prime A}\triangleq\bbnum 1+A\times M^{\prime L^{\prime A}}\quad.
\]
We denote that map temporarily by $\psi$. To be precise, $\psi$
is a function of $\phi$ and should be denoted by $\psi(\phi)$, but
we will write simply $\psi$ for brevity (since $\phi$ is fixed throughout
most of the derivation). We can implement $\psi:L^{A}\rightarrow L^{\prime A}$
by the following code:
\begin{equation}
\psi:L^{A}\rightarrow L^{\prime A}\quad,\quad\quad\psi\triangleq\,\begin{array}{|c||cc|}
 & \bbnum 1 & A\times M^{\prime L^{\prime A}}\\
\hline \bbnum 1 & \text{id} & \bbnum 0\\
A\times M^{L^{A}} & \bbnum 0 & \text{id}\boxtimes(\overline{\psi}^{\uparrow M}\bef\phi)
\end{array}\quad.\label{eq:list-monad-definition-of-psi}
\end{equation}
The foreign runner ($\text{frun}^{M,M^{\prime}}(\phi):T_{\text{List}}\leadsto T_{\text{List}}^{\prime}$)
is then implemented as
\[
\text{frun}^{M,M^{\prime}}\!:\,(M\leadsto M^{\prime})\rightarrow M^{L^{A}}\rightarrow M^{\prime L^{\prime A}}\!\quad,\quad\text{frun}^{M,M^{\prime}}\!(\phi^{:M\leadsto M^{\prime}})\triangleq\psi^{\uparrow M}\bef\phi\quad.
\]


\paragraph{Monadic naturality of \texttt{prod}}

When the monad $M$ is mapped to $M^{\prime}$ via a monad morphism
$\phi:M\leadsto M^{\prime}$, the \lstinline!prod! function with
type signature $\text{prod}_{M,L}:L\circ M\circ L\leadsto M\circ L$
is replaced by the corresponding function $\text{prod}_{M^{\prime},L^{\prime}}:L^{\prime}\circ M^{\prime}\circ L^{\prime}\leadsto M^{\prime}\circ L^{\prime}$.
The function $\text{prod}_{M^{\prime},L^{\prime}}$ has the same code
as $\text{prod}_{M,L}$ except for using the monad parameter $M^{\prime}$
instead of $M$. This monadic naturality\index{monadic naturality law!of prod for ListT@of \texttt{prod} for \texttt{ListT}}
property is expressed by the law analogous to Eq.~(\ref{eq:monadic-naturality-free-pointed-swap}):

\begin{wrapfigure}{l}{0.43\columnwidth}%
\vspace{-1.75\baselineskip}

\[
\xymatrix{\xyScaleY{1.2pc}\xyScaleX{1.6pc}L^{M^{L^{A}}}\ar[rd]\sb(0.45){\text{prod}_{M,L}}\ar[r]\sp(0.5){\psi^{\uparrow M\uparrow L}} & L^{M^{L^{\prime A}}}\ar[r]\sp(0.5){\phi^{\uparrow L}} & L^{M^{\prime L^{\prime A}}}\ar[r]\sp(0.5){\psi} & L^{\prime M^{\prime L^{\prime A}}}\ar[d]\sb(0.45){\,\text{prod}_{M^{\prime},L^{\prime}}}\\
 & M^{L^{A}}\ar[r]\sp(0.5){\psi^{\uparrow M}} & M^{L^{\prime A}}\ar[r]\sp(0.5){\phi} & M^{\prime L^{\prime A}}
}
\]
\vspace{-0.05\baselineskip}
\end{wrapfigure}%

~\vspace{-0.45\baselineskip}
\begin{equation}
\text{prod}_{M,L}\bef\psi^{\uparrow M}\bef\phi=\psi^{\uparrow M\uparrow L}\bef\phi^{\uparrow L}\bef\psi\bef\text{prod}_{M^{\prime},L^{\prime}}~~.\label{eq:monadic-naturality-law-of-prod-for-list-transformer}
\end{equation}

\noindent This law guarantees that the code of $\text{prod}_{M,L}$
works in the same way for all foreign monads $M$. We will verify
this law in Statement~\ref{subsec:Statement-laws-of-prod-for-effectful-list}
below.

\paragraph{Runner laws}

To show that the foreign runner is a monad morphism, begin with the
identity law:
\begin{align*}
{\color{greenunder}\text{expect }\text{pu}_{M^{\prime}\circ L^{\prime}}:}\quad & \text{pu}_{M\circ L}\bef\text{frun}\,(\phi)=\text{pu}_{L}\bef\gunderline{\text{pu}_{M}\bef\psi^{\uparrow M}}\bef\phi=\text{pu}_{L}\bef\psi\bef\gunderline{\text{pu}_{M}\bef\phi}\\
{\color{greenunder}\text{identity law of }\phi:}\quad & =\text{pu}_{L}\bef\psi\bef\text{pu}_{M^{\prime}}=\,\begin{array}{||cc|}
\bbnum 0 & a\rightarrow a\times\text{pu}_{M}(\text{Nil})\end{array}\,\bef\,\begin{array}{||cc|}
\text{id} & \bbnum 0\\
\bbnum 0 & \text{id}\boxtimes(\overline{\psi}^{\uparrow M}\bef\phi)
\end{array}\,\bef\text{pu}_{M^{\prime}}\\
 & =\,\begin{array}{||cc|}
\bbnum 0 & a\rightarrow a\times(\gunderline{\text{Nil}\triangleright\text{pu}_{M}\bef\overline{\psi}^{\uparrow M}\bef\phi})\end{array}\,\bef\text{pu}_{M^{\prime}}\\
 & =\,\,\begin{array}{||cc|}
\bbnum 0 & a\rightarrow a\times(\text{Nil}\triangleright\text{pu}_{M^{\prime}})\end{array}\,\bef\text{pu}_{M^{\prime}}=\text{pu}_{L^{\prime}}\bef\text{pu}_{M^{\prime}}=\text{pu}_{M^{\prime}\circ L^{\prime}}\quad.
\end{align*}
Here we used the following computation:
\[
\text{Nil}\triangleright\gunderline{\text{pu}_{M}\bef\psi^{\uparrow M}}\bef\phi=\text{Nil}\triangleright\psi\bef\gunderline{\text{pu}_{M}\bef\phi}=\text{Nil}\triangleright\text{pu}_{M^{\prime}}\quad.
\]
As part of this derivation, we have found the property
\begin{equation}
\text{pu}_{L}\bef\psi=\text{pu}_{L^{\prime}}\quad,\label{eq:puL-psi-derivation1}
\end{equation}
which resembles the identity law of a monad morphism for $\psi:L\leadsto L^{\prime}$.
However, $L$ and $L^{\prime}$ do not have the right monad structures
we can use here.

To verify the composition law, write its two sides separately:
\begin{align*}
{\color{greenunder}\text{left-hand side}:}\quad & \text{ftn}_{T}\bef\text{frun}\,(\phi)=\text{flm}_{M}(\text{prod})\bef\psi^{\uparrow M}\bef\phi=\text{flm}_{M}(\text{prod}\bef\psi^{\uparrow M})\bef\phi\\
{\color{greenunder}\phi\text{\textsf{'}s composition law}:}\quad & \quad=\phi\bef\text{flm}_{M^{\prime}}(\text{prod}\bef\psi^{\uparrow M}\bef\phi)\quad,\\
{\color{greenunder}\text{right-hand side}:}\quad & \big(\text{frun}\,(\phi)\big)^{\uparrow T}\bef\text{frun}\,(\phi)\bef\text{ftn}_{T^{\prime}}=\gunderline{(\psi^{\uparrow M}\bef\phi)^{\uparrow L\uparrow M}\bef\psi^{\uparrow M}\bef\phi}\bef\text{flm}_{M^{\prime}}(\text{prod})\\
{\color{greenunder}\text{naturality law of }\phi:}\quad & \quad=\phi\bef\big((\psi^{\uparrow M}\bef\phi)^{\uparrow L}\bef\psi\big)^{\uparrow M^{\prime}}\bef\text{flm}_{M^{\prime}}(\text{prod})=\phi\bef\text{flm}_{M^{\prime}}\big((\psi^{\uparrow M}\bef\phi)^{\uparrow L}\bef\psi\bef\text{prod}\big)\quad.
\end{align*}
The remaining difference is
\[
\text{prod}\bef\psi^{\uparrow M}\bef\phi\overset{?}{=}(\psi^{\uparrow M}\bef\phi)^{\uparrow L}\bef\psi\bef\text{prod}\quad.
\]
The last equation is the same as the monadic naturality law~(\ref{eq:monadic-naturality-law-of-prod-for-list-transformer})
of \lstinline!prod!.

\paragraph{Functor laws of \texttt{frun}}

To verify the functor laws of \lstinline!frun!, begin with the identity
law:
\[
\text{frun}\,(\text{id})=\psi(\text{id})\bef\text{id}=\,\begin{array}{||cc|}
\text{id} & \bbnum 0\\
\bbnum 0 & \text{id}\boxtimes(\overline{\psi(\text{id)}}^{\uparrow M}\bef\text{id})
\end{array}\,\bef\text{id}=\,\begin{array}{||cc|}
\text{id} & \bbnum 0\\
\bbnum 0 & \text{id}\boxtimes\text{id}
\end{array}\,=\text{id}\quad.
\]
Then verify the composition law, assuming $\phi_{1}:M\leadsto M^{\prime}$
and $\phi_{2}:M^{\prime}\leadsto M^{\prime\prime}$ are monad morphisms:
\begin{align*}
 & \text{frun}\,(\phi_{1})\bef\text{frun}\,(\phi_{2})=\psi^{\uparrow M}(\phi_{1})\bef\gunderline{\phi_{1}\bef\psi^{\uparrow M^{\prime}}(\phi_{2})}\bef\phi_{2}\\
{\color{greenunder}\text{naturality law of }\phi_{1}:}\quad & =\psi^{\uparrow M}(\phi_{1})\bef\psi^{\uparrow M}(\phi_{2})\bef\phi_{1}\bef\phi_{2}=\big(\psi(\phi_{1})\bef\psi(\phi_{2})\big)^{\uparrow M}\bef\phi_{1}\bef\phi_{2}\\
 & \overset{?}{=}\text{frun}\,(\phi_{1}\bef\phi_{2})=\psi(\phi_{1}\bef\phi_{2})^{\uparrow M}\bef\phi_{1}\bef\phi_{2}\quad.
\end{align*}
The remaining difference is
\[
\psi(\phi_{1})\bef\psi(\phi_{2})\overset{?}{=}\psi(\phi_{1}\bef\phi_{2})\quad,
\]
which we verify by writing
\begin{align*}
 & \psi(\phi_{1})\bef\psi(\phi_{2})=\,\begin{array}{||cc|}
\text{id} & \bbnum 0\\
\bbnum 0 & \text{id}\boxtimes(\overline{\psi(\phi_{1}\text{)}}^{\uparrow M}\bef\phi_{1})
\end{array}\,\bef\,\begin{array}{||cc|}
\text{id} & \bbnum 0\\
\bbnum 0 & \text{id}\boxtimes(\overline{\psi(\phi_{2}\text{)}}^{\uparrow M}\bef\phi_{2})
\end{array}\\
{\color{greenunder}\text{compute composition}:}\quad & =\,\begin{array}{||cc|}
\text{id} & \bbnum 0\\
\bbnum 0 & \text{id}\boxtimes(\gunderline{\overline{\psi(\phi_{1}\text{)}}^{\uparrow M}\bef\phi_{1}\bef\overline{\psi(\phi_{2}\text{)}}^{\uparrow M}\bef\phi_{2}})
\end{array}\\
{\color{greenunder}\text{inductive assumption}:}\quad & =\,\,\begin{array}{||cc|}
\text{id} & \bbnum 0\\
\bbnum 0 & \text{id}\boxtimes(\overline{\psi(\phi_{1}\bef\phi_{2}\text{)}}^{\uparrow M}\bef\phi_{1}\bef\phi_{2})
\end{array}\,=\psi(\phi_{1}\bef\phi_{2})\quad.
\end{align*}


\paragraph{Base runner laws}

The base runner ($\text{brun}:T^{A}\rightarrow M^{A}$) cannot be
implemented for arbitrary types $A$: since a list may be empty, it
is not always possible to extract a value of type $M^{A}$ out of
a given value of type $T_{\text{List}}^{M,A}$. However, for a monoid
type $R$ with binary operation $\oplus_{R}$ and empty element $e_{R}$,
the type signature $\text{List}^{R}\rightarrow R$ is implemented
by the standard \lstinline!reduce! operation: 
\[
\text{reduce}:\text{List}^{R}\rightarrow R\quad,\quad\quad\text{reduce}\triangleq\,\begin{array}{|c||c|}
 & R\\
\hline \bbnum 1 & 1\rightarrow e_{R}\\
R\times\text{List}^{R} & h\times t\rightarrow h\oplus_{R}\overline{\text{reduce}}\,(t)
\end{array}\quad.
\]
We can similarly implement a base runner (\lstinline!brun!) for the
transformer $T_{\text{List}}^{M,A}$ if we restrict its usage to \emph{monoid}
types $A=R$. The function \lstinline!brun! with the type signature
$M^{L^{R}}\rightarrow M^{R}$ aggregates all elements of the effectful
list into a single value of type $M^{R}$ (which is also a monoid
type):
\[
\text{brun}:M^{L^{R}}\rightarrow M^{R}\quad,\quad\quad\text{brun}\triangleq\text{flm}_{M}\bigg(\,\begin{array}{|c||c|}
 & M^{R}\\
\hline \bbnum 1 & 1\rightarrow\text{pu}_{M}(e_{R})\\
R\times M^{L^{R}} & h\times t\rightarrow\text{pu}_{M}(h)\oplus_{M}\overline{\text{brun}}\,(t)
\end{array}\,\bigg)\quad.
\]
Here we use the monoid $M^{R}$\textsf{'}s binary operation $\oplus_{M}$ defined
by
\begin{equation}
p^{:M^{R}}\oplus_{M}q^{:M^{R}}\triangleq p\triangleright\text{flm}_{M}\big(u^{:R}\rightarrow q\triangleright(v^{:R}\rightarrow u\oplus_{R}v)^{\uparrow M}\big)\quad.\label{eq:definition-of-oplus-M-monad-monoid-1}
\end{equation}

It can be shown that \lstinline!brun! satisfies the non-degeneracy
law:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{id}:}\quad & \text{flift}\bef\text{brun}=\text{pu}_{L}^{\uparrow M}\bef\text{flm}_{M}\bigg(\,\begin{array}{||c|}
1\rightarrow\text{pu}_{M}(e_{R})\\
r\times t\rightarrow\text{pu}_{M}(r)\oplus_{M}\overline{\text{brun}}\,(t)
\end{array}\,\bigg)\\
{\color{greenunder}\text{naturality of }\text{flm}_{M}:}\quad & =\text{flm}_{M}\bigg(\gunderline{\text{pu}_{L}}\bef\,\begin{array}{||c|}
1\rightarrow\text{pu}_{M}(e_{R})\\
r\times t\rightarrow\text{pu}_{M}(r)\oplus_{M}\overline{\text{brun}}\,(t)
\end{array}\,\bigg)\\
{\color{greenunder}\text{definition of }\text{pu}_{L}:}\quad & =\text{flm}_{M}\bigg(\,\begin{array}{||cc|}
\bbnum 0 & a\rightarrow a\times(\text{Nil}\triangleright\text{pu}_{M})\end{array}\,\bef\,\begin{array}{||c|}
1\rightarrow\text{pu}_{M}(e_{R})\\
r\times t\rightarrow\text{pu}_{M}(r)\oplus_{M}\overline{\text{brun}}\,(t)
\end{array}\,\bigg)\\
 & =\text{flm}_{M}(a\rightarrow\text{pu}_{M}(a)\oplus_{M}\gunderline{\text{brun}\,(\text{Nil}\triangleright\text{pu}_{M})})\\
{\color{greenunder}\text{use Eq.~(\ref{eq:listt-brun-derivation1})}:}\quad & =\text{flm}_{M}(a\rightarrow\gunderline{\text{pu}_{M}(a)\oplus\text{pu}_{M}(e_{R})})=\text{flm}_{M}(\gunderline{a\rightarrow\text{pu}_{M}(a)})=\text{flm}_{M}(\text{pu}_{M})=\text{id}\quad.
\end{align*}
Here we used the property that $\text{pu}_{M}(e_{R})$ is the unit
value for $\oplus_{M}$, and also computed
\begin{equation}
\text{brun}\,(\text{Nil}\triangleright\text{pu}_{M})=\text{Nil}\triangleright\gunderline{\text{pu}_{M}\bef\text{flm}_{M}}\bigg(\,\begin{array}{||c|}
1\rightarrow\text{pu}_{M}(e_{R})\\
r\times t\rightarrow\text{pu}_{M}(r)\oplus_{M}\overline{\text{brun}}\,(t)
\end{array}\,\bigg)=\text{pu}_{M}(e_{R})\quad.\label{eq:listt-brun-derivation1}
\end{equation}

The monad morphism identity law holds for \lstinline!brun!:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{pu}_{M}:}\quad & \text{pu}_{T}\bef\text{brun}=\text{pu}_{L}\bef\gunderline{\text{pu}_{M}\bef\text{flm}_{M}}\bigg(\,\begin{array}{||c|}
1\rightarrow\text{pu}_{M}(e_{R})\\
r\times t\rightarrow\text{pu}_{M}(r)\oplus_{M}\overline{\text{brun}}\,(t)
\end{array}\,\bigg)\\
{\color{greenunder}\text{identity law of }\text{flm}_{M}:}\quad & =\begin{array}{||cc|}
\bbnum 0 & a^{:R}\rightarrow a\times(\text{Nil}\triangleright\text{pu}_{M})\end{array}\,\bef\,\begin{array}{||c|}
1\rightarrow\text{pu}_{M}(e_{R})\\
r\times t\rightarrow\text{pu}_{M}(r)\oplus_{M}\overline{\text{brun}}\,(t)
\end{array}\\
{\color{greenunder}\text{matrix composition}:}\quad & =a^{:R}\rightarrow\text{pu}_{M}(a)\oplus_{M}\gunderline{\overline{\text{brun}}\,(\text{Nil}\triangleright\text{pu}_{M})}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:listt-brun-derivation1})}:}\quad & =a\rightarrow\text{pu}_{M}(a)\,\gunderline{\oplus_{M}\,\text{pu}_{M}(e_{R})}=a\rightarrow\text{pu}_{M}(a)=\text{pu}_{M}\quad.
\end{align*}

It is not clear whether the monad morphism composition law of \lstinline!brun!
holds (Problem~\ref{par:Problem-monads-5-2-1}). If the composition
law does not hold, the base runner \lstinline!brun! must be applied
to an entire monadic program. Running several parts of a program separately
and composing the results as values of type $M^{A}$ will not give
the same value as running the entire program.

\paragraph{Monadic naturality laws}

For \lstinline!flift!, the monadic naturality law is written as
\[
\text{flift}^{M}\bef\text{frun}\,(\phi)=\phi\bef\text{flift}^{M^{\prime}}\quad,
\]
where $\phi:M\leadsto M^{\prime}$ is an arbitrary natural transformation.
Begin with the left-hand side:
\begin{align*}
{\color{greenunder}\text{expect to equal }\phi\bef\text{flift}^{M^{\prime}}:}\quad & \text{flift}^{M}\bef\text{frun}\,(\phi)=\text{pu}_{L}^{\uparrow M}\bef\psi^{\uparrow M}\bef\phi=(\text{pu}_{L}\bef\psi)^{\uparrow M}\bef\phi\\
{\color{greenunder}\text{naturality law of }\phi:}\quad & =\phi\bef(\text{pu}_{L}\bef\psi)^{\uparrow M}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:puL-psi-derivation1})}:}\quad & =\phi\bef\text{pu}_{L^{\prime}}^{\uparrow M^{\prime}}=\phi\bef\text{flift}^{M^{\prime}}\quad.
\end{align*}

The monadic naturality law of \lstinline!brun! is written for any
monad morphism $\phi:M\leadsto M^{\prime}$:
\[
\text{brun}^{M}\bef\phi=\text{frun}\,(\phi)\bef\text{brun}^{M^{\prime}}\quad.
\]
Begin with the left-hand side:
\[
\text{flm}_{M}\bigg(\,\begin{array}{||c|}
1\rightarrow\text{pu}_{M}(e_{R})\\
r\times t\rightarrow\text{pu}_{M}(r)\oplus_{M}\overline{\text{brun}}\,(t)
\end{array}\,\bigg)\bef\phi=\phi\bef\text{flm}_{M^{\prime}}\bigg(\,\begin{array}{||c|}
1\rightarrow\text{pu}_{M}(e_{R})\\
r\times t\rightarrow\text{pu}_{M}(r)\oplus_{M}\overline{\text{brun}}\,(t)
\end{array}\,\bef\phi\bigg)\quad.
\]
Using the equality $\text{frun}\,(\phi)=\psi^{\uparrow M}\bef\phi=\phi\bef\psi^{\uparrow M^{\prime}}$,
we write the right-hand side as
\begin{align*}
 & \text{frun}\,(\phi)\bef\text{brun}=\phi\bef\gunderline{\psi^{\uparrow M^{\prime}}\bef\text{flm}_{M^{\prime}}}\bigg(\,\begin{array}{||c|}
1\rightarrow\text{pu}_{M^{\prime}}(e_{R})\\
r\times t\rightarrow\text{pu}_{M^{\prime}}(r)\oplus_{M^{\prime}}\overline{\text{brun}}\,(t)
\end{array}\,\bigg)\\
{\color{greenunder}\text{naturality law of }\text{flm}_{M^{\prime}}:}\quad & =\phi\bef\text{flm}_{M^{\prime}}\bigg(\psi\bef\,\begin{array}{||c|}
1\rightarrow\text{pu}_{M^{\prime}}(e_{R})\\
r\times t\rightarrow\text{pu}_{M^{\prime}}(r)\oplus_{M^{\prime}}\overline{\text{brun}}\,(t)
\end{array}\,\bigg)\quad.
\end{align*}
The remaining difference is
\[
\begin{array}{||c|}
1\rightarrow\text{pu}_{M}(e_{R})\\
r\times t\rightarrow\text{pu}_{M}(r)\oplus_{M}\overline{\text{brun}}{}^{M}(t)
\end{array}\,\bef\phi\overset{?}{=}\psi\bef\,\begin{array}{||c|}
1\rightarrow\text{pu}_{M^{\prime}}(e_{R})\\
r\times t\rightarrow\text{pu}_{M^{\prime}}(r)\oplus_{M^{\prime}}\overline{\text{brun}}{}^{M^{\prime}}(t)
\end{array}\quad.
\]
Rewrite the left-hand side:
\begin{align*}
 & \begin{array}{||c|}
1\rightarrow\text{pu}_{M}(e_{R})\\
r\times t\rightarrow\text{pu}_{M}(r)\oplus_{M}\overline{\text{brun}}{}^{M}(t)
\end{array}\,\bef\phi=\,\begin{array}{||c|}
1\rightarrow e_{R}\triangleright\gunderline{\text{pu}_{M}\bef\phi}\\
r\times t\rightarrow\phi\big(\text{pu}_{M}(r)\oplus_{M}\overline{\text{brun}}{}^{M}(t)\big)
\end{array}\\
 & =\,\begin{array}{||c|}
1\rightarrow e_{R}\triangleright\text{pu}_{M^{\prime}}\\
r\times t\rightarrow\phi\big(\text{pu}_{M}(r)\oplus_{M}\overline{\text{brun}}{}^{M}(t)\big)
\end{array}\quad.
\end{align*}
Rewrite the right-hand side:
\begin{align*}
 & \psi\bef\,\begin{array}{||c|}
1\rightarrow\text{pu}_{M^{\prime}}(e_{R})\\
r\times t\rightarrow\text{pu}_{M^{\prime}}(r)\oplus_{M^{\prime}}\overline{\text{brun}}{}^{M^{\prime}}(t)
\end{array}\\
{\color{greenunder}\text{definition of }\psi:}\quad & =\,\begin{array}{||cc|}
\text{id} & \bbnum 0\\
\bbnum 0 & \text{id}\boxtimes\text{frun}\,(\phi)
\end{array}\,\bef\,\begin{array}{||c|}
1\rightarrow\text{pu}_{M^{\prime}}(e_{R})\\
r\times t\rightarrow\text{pu}_{M^{\prime}}(r)\oplus_{M^{\prime}}\overline{\text{brun}}{}^{M^{\prime}}(t)
\end{array}\\
{\color{greenunder}\text{matrix composition}:}\quad & =\,\,\begin{array}{||c|}
1\rightarrow\text{pu}_{M^{\prime}}(e_{R})\\
r\times t\rightarrow\text{pu}_{M^{\prime}}(r)\oplus_{M^{\prime}}\big(t\triangleright\gunderline{\text{frun}\,(\phi)\bef\overline{\text{brun}}{}^{M^{\prime}}}\big)
\end{array}\\
{\color{greenunder}\text{inductive assumption}:}\quad & =\,\begin{array}{||c|}
1\rightarrow\text{pu}_{M^{\prime}}(e_{R})\\
r\times t\rightarrow\text{pu}_{M^{\prime}}(r)\oplus_{M^{\prime}}\big(t\triangleright\text{brun}^{M}\bef\phi\big)
\end{array}\quad.
\end{align*}
The remaining difference is in the last rows of the matrices:
\[
\phi\big(\text{pu}_{M}(r)\oplus_{M}\overline{\text{brun}}{}^{M}(t)\big)\overset{?}{=}\text{pu}_{M^{\prime}}(r)\oplus_{M^{\prime}}\phi\big(t\triangleright\text{brun}^{M}\big)\quad.
\]
This equality will be proved if we prove the \index{monadic naturality law!of monoid composition}monadic
naturality of $\oplus_{M}$ defined by Eq.~(\ref{eq:definition-of-oplus-M-monad-monoid-1}):
\[
\phi(p^{:M^{R}}\oplus_{M}q^{:M^{R}})=\phi(p)\oplus_{M^{\prime}}\phi(q)\quad.
\]
A proof is given by the following derivation:
\begin{align*}
{\color{greenunder}\text{expect to equal }\phi(p)\oplus_{M}\phi(q):}\quad & (p\oplus_{M}q)\triangleright\phi=p\triangleright\text{flm}_{M}\big(u\rightarrow q\triangleright(v\rightarrow u\oplus_{R}v)^{\uparrow M}\big)\bef\phi\\
{\color{greenunder}\text{composition law of }\phi:}\quad & =p\triangleright\phi\bef\text{flm}_{M^{\prime}}(u\rightarrow q\triangleright(v\rightarrow u\oplus_{R}v\gunderline{)^{\uparrow M}\bef\phi})\\
{\color{greenunder}\text{naturality law of }\phi:}\quad & =\phi(p)\triangleright\text{flm}_{M^{\prime}}(u\rightarrow\phi(q)\triangleright(v\rightarrow u\oplus_{R}v)^{\uparrow M^{\prime}})\\
{\color{greenunder}\text{definition~(\ref{eq:definition-of-oplus-M-monad-monoid-1}) of }\oplus_{M}:}\quad & =\phi(p)\oplus_{M}\phi(q)\quad.
\end{align*}

$\square$

We conclude this section with derivations of some properties that
were used in the proofs above. 

The next statement shows that $M^{L^{A}}$ is a monoid for any fixed
type $A$.

\subsubsection{Statement \label{subsec:Statement-monoid-operation-comb-for-effectful-list}\ref{subsec:Statement-monoid-operation-comb-for-effectful-list}}

Given any monad $M$, define the functor $L$ recursively by 
\[
L^{A}\triangleq\bbnum 1+A\times M^{L^{A}}\quad.
\]
Denote $\text{Nil}\triangleq1+\bbnum 0^{:A\times M^{L^{A}}}$. Then
the function \lstinline!comb! defined by Eq.~(\ref{eq:definition-of-comb-for-effectful-list})
satisfies:
\begin{align*}
{\color{greenunder}\text{identity laws}:}\quad & \text{comb}\,(\text{Nil}\triangleright\text{pu}_{M})(m^{:M^{L^{A}}})=m\quad,\quad\quad\text{comb}\,(m^{:M^{L^{A}}})(\text{Nil}\triangleright\text{pu}_{M})=m\quad,\\
{\color{greenunder}\text{associativity law}:}\quad & \text{comb}\,(x)\big(\text{comb}\,(y)(z)\big)=\text{comb}\,\big(\text{comb}\,(x)(y)\big)(z)\quad.
\end{align*}
These laws show that the type $M^{L^{A}}$ is a monoid with empty
value $\text{pu}_{M}(\text{Nil})$.

\subparagraph{Proof}

To verify the left identity law:
\begin{align*}
{\color{greenunder}\text{expect to equal }m:}\quad & \text{comb}\,(\text{Nil}\triangleright\text{pu}_{M})(m^{:M^{L^{A}}})\\
 & =\text{Nil}\triangleright\gunderline{\text{pu}_{M}\triangleright\text{flm}_{M}}\bigg(\,\begin{array}{|c||c|}
 & M^{L^{A}}\\
\hline \bbnum 1 & 1\rightarrow m\\
A\times M^{L^{A}} & a\times p\rightarrow\text{pu}_{M}\big(\bbnum 0+a\times\overline{\text{comb}}\,(p)(m)\big)
\end{array}\,\bigg)\\
{\color{greenunder}\text{identity law of }M:}\quad & =\text{Nil}\triangleright\,\begin{array}{|c||c|}
 & M^{L^{A}}\\
\hline \bbnum 1 & \gunderline{1\rightarrow m}\\
A\times M^{L^{A}} & a\times p\rightarrow\text{pu}_{M}\big(\bbnum 0+a\times\overline{\text{comb}}\,(p)(m)\big)
\end{array}\,=m\quad.
\end{align*}
To verify the right identity law:
\begin{align*}
{\color{greenunder}\text{expect to equal }m:}\quad & \text{comb}\,(m^{:M^{L^{A}}})(\text{Nil}\triangleright\text{pu}_{M})\\
 & =m\triangleright\text{flm}_{M}\bigg(\,\begin{array}{|c||c|}
 & M^{L^{A}}\\
\hline \bbnum 1 & 1\rightarrow\text{Nil}\triangleright\text{pu}_{M}\\
A\times M^{L^{A}} & a\times p\rightarrow\text{pu}_{M}\big(\bbnum 0+a\times\gunderline{\overline{\text{comb}}\,(p)(\text{Nil}\triangleright\text{pu}_{M})}\big)
\end{array}\,\bigg)\\
{\color{greenunder}\text{inductive assumption}:}\quad & =\,m\triangleright\text{flm}_{M}\bigg(\,\begin{array}{|c||c|}
 & M^{L^{A}}\\
\hline \bbnum 1 & 1\rightarrow\text{Nil}\triangleright\text{pu}_{M}\\
A\times M^{L^{A}} & a\times p\rightarrow\text{pu}_{M}\big(\bbnum 0+a\times p\big)
\end{array}\,\bigg)\\
 & =m\triangleright\text{flm}_{M}\bigg(\,\begin{array}{||c|}
(1\rightarrow1+\bbnum 0)\bef\text{pu}_{M}\\
(a\times p\rightarrow\bbnum 0+a\times p\big)\bef\text{pu}_{M}
\end{array}\,\bigg)=m\triangleright\gunderline{\text{flm}_{M}(\gunderline{\text{id}\bef\text{pu}_{M}})}=m\quad.
\end{align*}
To verify the associativity law of \lstinline!comb!, it is convenient
to express \lstinline!comb! through a helper function $\xi$:
\begin{align}
 & \text{comb}\,(m)(n)\triangleq m\triangleright\text{flm}_{M}(n\triangleright\xi)=m\triangleright(n\triangleright\xi)^{\uparrow M}\bef\text{ftn}_{M}\quad,\label{eq:comb-defined-via-helper-function-xi}\\
{\color{greenunder}\text{where }\xi\text{ is defined by}:}\quad & n\triangleright\xi\triangleq\,\begin{array}{|c||c|}
 & M^{L^{A}}\\
\hline \bbnum 1 & 1\rightarrow n\\
A\times M^{L^{A}} & a\times p\rightarrow\text{pu}_{M}\big(\bbnum 0^{:\bbnum 1}+a\times\overline{\text{comb}}\,(p)(n)\big)
\end{array}\quad.\nonumber 
\end{align}
We then write the two sides of the associativity law. The left-hand
side:
\[
\text{comb}\,(x)\big(\text{comb}\,(y)(z)\big)=x\triangleright\,\begin{array}{||c|}
1\rightarrow\text{comb}\,(y)(z)\\
a\times p\rightarrow\text{pu}_{M}\big(\bbnum 0+a\times\gunderline{\overline{\text{comb}}\,(p)(\text{comb}\,(y)(z))}\big)
\end{array}^{\uparrow M}\bef\text{ftn}_{M}\quad.
\]
Use the inductive assumption to rewrite the last expression as
\[
x\triangleright\,\begin{array}{||c|}
1\rightarrow\text{comb}\,(y)(z)\\
a\times p\rightarrow\text{pu}_{M}\big(\bbnum 0+a\times\overline{\text{comb}}\,(\text{comb}\,(p)(y))(z)\big)
\end{array}^{\uparrow M}\bef\text{ftn}_{M}\quad.
\]
The right-hand side:
\begin{align*}
 & \text{comb}\,\big(\text{comb}\,(x)(y)\big)(z)=\text{comb}\,(x)(y)\triangleright(z\triangleright\xi)^{\uparrow M}\bef\text{ftn}_{M}=x\triangleright(y\triangleright\xi)^{\uparrow M}\bef\gunderline{\text{ftn}_{M}\bef(z\triangleright\xi)^{\uparrow M}}\bef\text{ftn}_{M}\\
 & =x\triangleright(y\triangleright\xi)^{\uparrow M}\bef(z\triangleright\xi)^{\uparrow M\uparrow M}\bef\gunderline{\text{ftn}_{M}\bef\text{ftn}_{M}}=x\triangleright\big((y\triangleright\xi)\bef(z\triangleright\xi)^{\uparrow M}\bef\text{ftn}_{M}\big)^{\uparrow M}\bef\text{ftn}_{M}\quad.
\end{align*}
Write out the expression $(y\triangleright\xi)\bef(z\triangleright\xi)^{\uparrow M}\bef\text{ftn}_{M}$
(having type $\bbnum 1+A\times M^{L^{A}}\rightarrow M^{L^{A}}$) separately:
\begin{align*}
 & (y\triangleright\xi)\bef(z\triangleright\xi)^{\uparrow M}\bef\text{ftn}_{M}\\
 & =\,\begin{array}{||c|}
1\rightarrow y\\
a\times p\rightarrow\text{pu}_{M}\big(\bbnum 0+a\times\overline{\text{comb}}\,(p)(y)\big)
\end{array}\,\bef(z\triangleright\xi)^{\uparrow M}\bef\text{ftn}_{M}\\
 & =\,\,\begin{array}{||c|}
1\rightarrow\gunderline{y\triangleright(z\triangleright\xi)^{\uparrow M}\bef\text{ftn}_{M}}\\
a\times p\rightarrow\big(\bbnum 0+a\times\overline{\text{comb}}\,(p)(y)\big)\triangleright\gunderline{\text{pu}_{M}}\bef(z\triangleright\xi)^{\uparrow M}\bef\gunderline{\text{ftn}_{M}}
\end{array}\\
 & =\,\begin{array}{||c|}
1\rightarrow\text{comb}\,(y)(z)\\
a\times p\rightarrow\big(\bbnum 0+a\times\overline{\text{comb}}\,(p)(y)\big)\triangleright(z\triangleright\xi)
\end{array}\quad.
\end{align*}
The difference between the two sides is only in the last rows of the
matrices:
\[
\text{pu}_{M}\big(\bbnum 0+a\times\overline{\text{comb}}\,(\text{comb}\,(p)(y))(z)\big)\overset{?}{=}\big(\bbnum 0+a\times\overline{\text{comb}}\,(p)(y)\big)\triangleright(z\triangleright\xi)\quad.
\]
It remains to simplify the right-hand side above and make it equal
to the left-hand side:
\begin{align*}
 & \big(\bbnum 0+a\times\overline{\text{comb}}\,(p)(y)\big)\triangleright(z\triangleright\xi)\\
 & =\big(\bbnum 0+a\times\overline{\text{comb}}\,(p)(y)\big)\triangleright\,\begin{array}{||c|}
1\rightarrow z\\
a\times p\rightarrow\text{pu}_{M}\big(\bbnum 0+a\times\overline{\text{comb}}\,(p)(z)\big)
\end{array}\\
 & =\text{pu}_{M}\big(\bbnum 0+a\times\overline{\text{comb}}\,(\overline{\text{comb}}\,(p)(y))(z)\big)\quad.
\end{align*}
This completes the proof.

\subsubsection{Statement \label{subsec:Statement-distributive-law-of-comb-for-effectful-list}\ref{subsec:Statement-distributive-law-of-comb-for-effectful-list}}

The function \lstinline!comb! defined by Eq.~(\ref{eq:definition-of-comb-for-effectful-list})
satisfies the distributive law\index{distributive law!of comb@of \texttt{comb}}:
\[
\big(\text{comb}\,(p^{:T^{T^{A}}})(q^{:T^{T^{A}}})\big)\triangleright\text{ftn}_{T}=\text{comb}\,(p\triangleright\text{ftn}_{T})(q\triangleright\text{ftn}_{T})\quad,
\]
where we denoted $T^{A}\triangleq M^{L^{A}}$ for brevity, and $\text{ftn}_{T}$
is defined by Eq.~(\ref{eq:def-pure-flatten-via-prod-for-list-monad-transformer}).

\subparagraph{Proof}

Begin with the left-hand side of the distributive law and use Eq.~(\ref{eq:comb-defined-via-helper-function-xi}):
\begin{align*}
 & \big(\text{comb}\,(p)(q)\big)\triangleright\text{ftn}_{T}=p\triangleright\text{flm}_{M}(q\triangleright\xi)\triangleright\text{ftn}_{T}=p\triangleright\text{flm}_{M}(q\triangleright\xi)\bef\text{flm}_{M}(\text{prod})\\
{\color{greenunder}\text{associativity of }\text{flm}_{M}:}\quad & =p\triangleright\text{flm}_{M}((q\triangleright\xi)\bef\text{flm}_{M}(\text{prod}))\quad.
\end{align*}
Rewrite the right-hand side of the distributive law:
\begin{align*}
 & \text{comb}\,(p\triangleright\text{ftn}_{T})(q\triangleright\text{ftn}_{T})=p\triangleright\gunderline{\text{ftn}_{T}}\triangleright\text{flm}_{M}(q\triangleright\text{ftn}_{T}\triangleright\xi)\\
 & =p\triangleright\text{flm}_{M}(\text{prod})\bef\text{flm}_{M}(q\triangleright\text{ftn}_{T}\triangleright\xi)\\
{\color{greenunder}\text{associativity of }\text{flm}_{M}:}\quad & =p\triangleright\text{flm}_{M}\big(\text{prod}\bef\text{flm}_{M}(q\triangleright\text{ftn}_{T}\triangleright\xi)\big)\quad.
\end{align*}
It remains to prove the following equality between functions of type
$L^{T^{A}}\rightarrow T^{A}$:
\[
\text{prod}\bef\text{flm}_{M}(q\triangleright\text{ftn}_{T}\triangleright\xi)\overset{?}{=}(q\triangleright\xi)\bef\text{flm}_{M}(\text{prod})\quad.
\]
Since we have no matrix representation for $\text{flm}_{M}$, it is
inconvenient to use matrices at this step. Instead, we substitute
an arbitrary value of type $L^{T^{A}}\cong\bbnum 1+T^{A}\times T^{T^{A}}$
into both sides of the equation above. A value of type $L^{T^{A}}$
has two cases, $\text{Nil}$ and $h^{:T^{A}}\times t^{:T^{T^{A}}}\!$.
Substitute $\text{Nil}$ into the left-hand side:
\begin{align*}
 & \gunderline{\text{Nil}\triangleright\text{prod}}\bef\text{flm}_{M}(q\triangleright\text{ftn}_{T}\triangleright\xi)=\text{Nil}\triangleright\gunderline{\text{pu}_{M}\bef\text{flm}_{M}}(q\triangleright\text{ftn}_{T}\triangleright\xi)\\
{\color{greenunder}\text{identity law of }M:}\quad & =\text{Nil}\triangleright(q\triangleright\text{ftn}_{T}\triangleright\xi)\quad.
\end{align*}
Since 
\[
\text{Nil}\triangleright(s\triangleright\xi)=\,\begin{array}{|cc|}
1 & \bbnum 0\end{array}\,\triangleright\,\begin{array}{||c|}
1\rightarrow s\\
a\times p\rightarrow\text{pu}_{M}\big(\bbnum 0+a\times\overline{\text{comb}}\,(p)(s)\big)
\end{array}\,=s\quad,
\]
we can simplify
\[
\text{Nil}\triangleright(q\triangleright\text{ftn}_{T}\triangleright\xi)=q\triangleright\text{ftn}_{T}\quad.
\]
Substituting $\text{Nil}$ into the right-hand side yields:
\[
\gunderline{\text{Nil}\triangleright(q\triangleright\xi)}\triangleright\text{flm}_{M}(\text{prod})=q\triangleright\gunderline{\text{flm}_{M}(\text{prod})}=q\triangleright\text{ftn}_{T}\quad.
\]
Both sides are now equal.

It remains to substitute a value of the form $\bbnum 0+h^{:T^{A}}\times t^{:T^{T^{A}}}$.
For the left-hand side:
\begin{align*}
 & (\bbnum 0+h\times t)\triangleright\text{prod}\bef\text{flm}_{M}(q\triangleright\text{ftn}_{T}\triangleright\xi)\\
 & =(\bbnum 0+h\times t)\triangleright\,\begin{array}{||c|}
1\rightarrow\text{Nil}\triangleright\text{pu}_{M}\\
m\times p\rightarrow\text{comb}\,(m)(p\triangleright\text{flm}_{M}(\overline{\text{prod}}))
\end{array}\,\bef\text{flm}_{M}(q\triangleright\text{ftn}_{T}\triangleright\xi)\\
{\color{greenunder}\text{apply matrix}:}\quad & =\big(\text{comb}\,(h)(t\triangleright\text{ftn}_{T})\big)\triangleright\text{flm}_{M}(q\triangleright\text{ftn}_{T}\triangleright\xi)\quad.
\end{align*}
Substitute $\bbnum 0+h\times t$ into the right-hand side:
\begin{align*}
 & (\bbnum 0+h\times t)\triangleright(q\triangleright\xi)\bef\text{flm}_{M}(\text{prod})\\
{\color{greenunder}\text{definition of }c:}\quad & =(\bbnum 0+h\times t)\triangleright\,\begin{array}{||c|}
1\rightarrow q\triangleright\text{flm}_{M}(\text{prod})\\
a\times p\rightarrow\big(\bbnum 0+a\times\overline{\text{comb}}\,(p)(q)\big)\triangleright\gunderline{\text{pu}_{M}\bef\text{flm}_{M}}(\text{prod})
\end{array}\\
{\color{greenunder}\text{apply matrix function}:}\quad & =\big(\bbnum 0+h\times\overline{\text{comb}}\,(t)(q)\big)\triangleright\text{prod}\\
{\color{greenunder}\text{definition of }\text{prod}:}\quad & =\big(\bbnum 0+h\times\overline{\text{comb}}\,(t)(q)\big)\triangleright\,\begin{array}{||c|}
1\rightarrow\text{Nil}\triangleright\text{pu}_{M}\\
m\times p\rightarrow\text{comb}\,(m)(p\triangleright\overline{\text{ftn}}_{T})
\end{array}\\
{\color{greenunder}\text{apply matrix}:}\quad & =\text{comb}\,(h)\big(\gunderline{(\overline{\text{comb}}\,(t)(q))\triangleright\overline{\text{ftn}}_{T}}\big)\\
{\color{greenunder}\text{inductive assumption}:}\quad & =\text{comb}\,(h)\big(\text{comb}\,(t\triangleright\text{ftn}_{T})(q\triangleright\text{ftn}_{T})\big)\\
{\color{greenunder}\text{associativity law of }\text{comb}:}\quad & =\gunderline{\text{comb}}\,\big(\text{comb}\,(h)((t\triangleright\text{ftn}_{T}))\big)(q\triangleright\text{ftn}_{T})\\
{\color{greenunder}\text{definition~(\ref{eq:definition-of-comb-for-effectful-list}) of }\text{comb}:}\quad & =\big(\text{comb}\,(h)((t\triangleright\text{ftn}_{T}))\big)\triangleright\text{flm}_{M}(q\triangleright\text{ftn}_{T}\triangleright\xi)\quad.
\end{align*}
The two sides are now equal. (The associativity law of \lstinline!comb!
was proved in Statement~\ref{subsec:Statement-monoid-operation-comb-for-effectful-list}.)

\subsubsection{Statement \label{subsec:Statement-monadic-naturality-of-comb-for-effectful-list}\ref{subsec:Statement-monadic-naturality-of-comb-for-effectful-list}}

The function \lstinline!comb! defined by Eq.~(\ref{eq:comb-defined-via-helper-function-xi})
satisfies the monadic naturality law with respect to the foreign monad
$M$: For any two monads $M$ and $M^{\prime}$ with a monad morphism
$\phi:M\leadsto M^{\prime}$, we define $\psi$ (which depends on
$\phi$) by Eq.~(\ref{eq:list-monad-definition-of-psi}). The law
is then written as
\[
\big(\text{comb}\,(p^{:T^{A}})(q^{:T^{A}})\big)\triangleright\psi^{\uparrow M}\bef\phi=\text{comb}\,(p\triangleright\psi^{\uparrow M}\bef\phi)(q\triangleright\psi^{\uparrow M}\bef\phi)\quad.
\]
Note that \lstinline!comb! must use the monad $M^{\prime}$ in the
right-hand side of the law.

\subparagraph{Proof}

We write the left-hand side of the law:
\begin{align*}
 & \text{comb}\,(p)(q)\triangleright\psi^{\uparrow M}\bef\phi=p\triangleright\text{flm}_{M}(q\triangleright\xi)\bef\gunderline{\psi^{\uparrow M}\bef\phi}\\
{\color{greenunder}\text{naturality law of }\phi:}\quad & =p\triangleright\gunderline{\text{flm}_{M}(q\triangleright\xi)\bef\phi}\bef\psi^{\uparrow M^{\prime}}\\
{\color{greenunder}\text{composition law of }\phi:}\quad & =p\triangleright\phi\bef\text{flm}_{M^{\prime}}\big((q\triangleright\xi)\bef\phi\big)\,\gunderline{\bef\psi^{\uparrow M^{\prime}}}\\
{\color{greenunder}\text{naturality law of }\text{flm}_{M^{\prime}}:}\quad & =p\triangleright\phi\bef\text{flm}_{M^{\prime}}\big((q\triangleright\xi)\bef\phi\bef\psi^{\uparrow M^{\prime}}\big)\quad.
\end{align*}
The right-hand side is rewritten as
\begin{align*}
 & \text{comb}\,(p\triangleright\psi^{\uparrow M}\bef\phi)(q\triangleright\psi^{\uparrow M}\bef\phi)=p\triangleright\gunderline{\psi^{\uparrow M}\bef\phi}\bef\text{flm}_{M^{\prime}}\big(q\triangleright\gunderline{\psi^{\uparrow M}\bef\phi}\bef\xi\big)\\
{\color{greenunder}\text{naturality law of }\phi:}\quad & =p\triangleright\phi\bef\gunderline{\psi^{\uparrow M^{\prime}}\bef\text{flm}_{M^{\prime}}}\big(q\triangleright\phi\bef\psi^{\uparrow M^{\prime}}\bef\xi\big)\\
{\color{greenunder}\text{naturality of }\text{flm}_{M^{\prime}}:}\quad & =p\triangleright\phi\bef\text{flm}_{M^{\prime}}\big(\psi\bef(q\triangleright\phi\bef\psi^{\uparrow M^{\prime}}\bef\xi)\big)\quad.
\end{align*}
The remaining difference between the two sides is the following equality:
\[
(q\triangleright\xi)\bef\phi\bef\psi^{\uparrow M^{\prime}}\overset{?}{=}\psi\bef(q\triangleright\phi\bef\psi^{\uparrow M^{\prime}}\bef\xi)\quad.
\]
This should hold for any $q^{:T^{A}}$. Write the two sides separately:
\begin{align*}
{\color{greenunder}\text{left-hand side}:}\quad & (q\triangleright\xi)\bef\phi\bef\psi^{\uparrow M^{\prime}}=\,\begin{array}{||c|}
1\rightarrow q\triangleright\phi\bef\psi^{\uparrow M^{\prime}}\\
a\times p\rightarrow\big(\bbnum 0+a\times\overline{\text{comb}}\,(p)(q)\big)\triangleright\gunderline{\text{pu}_{M}\bef\phi\bef\psi^{\uparrow M^{\prime}}}
\end{array}\\
 & \quad=\,\begin{array}{||c|}
1\rightarrow q\triangleright\phi\bef\psi^{\uparrow M^{\prime}}\\
a\times p\rightarrow\big(\bbnum 0+a\times\overline{\text{comb}}\,(p)(q)\big)\triangleright\psi\bef\text{pu}_{M^{\prime}}
\end{array}\quad,\\
{\color{greenunder}\text{right-hand side}:}\quad & \psi\bef(q\triangleright\phi\triangleright\psi^{\uparrow M^{\prime}}\triangleright\xi)\\
 & \quad=\,\begin{array}{||cc|}
\text{id} & \bbnum 0\\
\bbnum 0 & \text{id}\boxtimes(\phi\bef\overline{\psi}^{\uparrow M^{\prime}})
\end{array}\,\bef\,\begin{array}{||c|}
1\rightarrow q\triangleright\phi\triangleright\psi^{\uparrow M^{\prime}}\\
a\times p\rightarrow\big(\bbnum 0+a\times\overline{\text{comb}}\,(p)(q\triangleright\phi\triangleright\psi^{\uparrow M^{\prime}})\big)\triangleright\text{pu}_{M^{\prime}}
\end{array}\\
 & \quad=\,\,\begin{array}{||c|}
1\rightarrow q\triangleright\phi\bef\psi^{\uparrow M^{\prime}}\\
a\times p\rightarrow\big(\bbnum 0+a\times\overline{\text{comb}}\,(p\triangleright\phi\bef\overline{\psi}^{\uparrow M^{\prime}})(q\triangleright\phi\bef\psi^{\uparrow M^{\prime}})\big)\triangleright\text{pu}_{M^{\prime}}
\end{array}\quad.
\end{align*}
By the inductive assumption,
\[
\overline{\text{comb}}\,(p\triangleright\phi\bef\overline{\psi}^{\uparrow M^{\prime}})(q\triangleright\phi\bef\psi^{\uparrow M^{\prime}})=\big(\text{comb}\,(p)(q)\big)\triangleright\phi\bef\psi^{\uparrow M^{\prime}}\quad.
\]
So, the remaining difference between the two sides is
\[
\big(\bbnum 0+a\times\overline{\text{comb}}\,(p)(q)\big)\triangleright\psi\overset{?}{=}\bbnum 0+a\times\big(\text{comb}\,(p)(q)\big)\triangleright\phi\bef\psi^{\uparrow M^{\prime}}\quad.
\]
Using the definition~(\ref{eq:list-monad-definition-of-psi}) of
$\psi$, we find
\begin{align*}
 & \big(\bbnum 0+a\times\overline{\text{comb}}\,(p)(q)\big)\triangleright\psi=\big(\bbnum 0+a\times\overline{\text{comb}}\,(p)(q)\big)\triangleright\,\begin{array}{||cc|}
\text{id} & \bbnum 0\\
\bbnum 0 & \text{id}\boxtimes(\phi\bef\overline{\psi}^{\uparrow M^{\prime}})
\end{array}\\
 & =a\times\big(\overline{\text{comb}}\,(p)(q)\big)\triangleright\phi\bef\overline{\psi}^{\uparrow M^{\prime}}\quad,
\end{align*}
which equals the right-hand side above. This completes the proof.

\subsubsection{Statement \label{subsec:Statement-laws-of-prod-for-effectful-list}\ref{subsec:Statement-laws-of-prod-for-effectful-list}}

The function \lstinline!prod! defined by Eq.~(\ref{eq:definition-of-prod-for-list-monad-transformer})
satisfies Eqs.~(\ref{eq:identity-laws-of-prod-for-effectful-list})\textendash (\ref{eq:monadic-naturality-law-of-prod-for-list-transformer}).

\subparagraph{Proof}

To verify the left identity law of \lstinline!prod!, note that $\text{Nil}\triangleright\text{prod}=\text{pu}_{M}(\text{Nil})$
and write:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{id}:}\quad & \text{pu}_{L}\bef\text{prod}\\
 & =\,\begin{array}{||cc|}
\bbnum 0 & a\rightarrow a\times(\text{Nil}\triangleright\text{pu}_{M})\end{array}\,\bef\,\begin{array}{||c|}
1\rightarrow\text{Nil}\triangleright\text{pu}_{M}\\
m\times p\rightarrow\text{comb}\,(m)(p\triangleright\overline{\text{prod}}^{\uparrow M}\bef\text{ftn}_{M})
\end{array}\\
 & =a^{:M^{L^{A}}}\rightarrow\text{comb}\,(a)(\text{Nil}\triangleright\gunderline{\text{pu}_{M}\bef\overline{\text{prod}}^{\uparrow M}}\bef\text{ftn}_{M})\\
 & =a\rightarrow\text{comb}\,(a)(\text{Nil}\triangleright\text{prod}\bef\gunderline{\text{pu}_{M}\bef\text{ftn}_{M}})=a\rightarrow\text{comb}\,(a)(\gunderline{\text{Nil}\triangleright\text{prod}})\\
 & =a\rightarrow\gunderline{\text{comb}\,(a)(\text{Nil}\triangleright\text{pu}_{M})}=a\rightarrow a=\text{id}\quad.
\end{align*}
In the last line, we used an identity law of \lstinline!comb! from
Statement~\ref{subsec:Statement-monoid-operation-comb-for-effectful-list}.

To verify the right identity law of \lstinline!prod!, show that its
left-hand side equals $\text{pu}_{M}$:
\begin{align*}
 & \text{pu}_{T}^{\uparrow L}\bef\text{prod}=(\text{pu}_{L}\bef\text{pu}_{M})^{\uparrow L}\bef\text{prod}\\
 & =\,\begin{array}{|c||cc|}
 & \bbnum 1 & M^{L^{A}}\times M^{L^{M^{L^{A}}}}\\
\hline \bbnum 1 & \text{id} & \bbnum 0\\
A\times M^{L^{A}} & \bbnum 0 & \text{pu}_{T}\boxtimes\overline{\text{pu}}_{T}^{\uparrow L\uparrow M}
\end{array}\,\bef\,\begin{array}{|c||c|}
 & M^{L^{A}}\\
\hline \bbnum 1 & 1\rightarrow\text{Nil}\triangleright\text{pu}_{M}\\
M^{L^{A}}\times M^{L^{M^{L^{A}}}} & m\times p\rightarrow\text{comb}\,(m)(p\triangleright\overline{\text{prod}}^{\uparrow M}\bef\text{ftn}_{M})
\end{array}\\
 & =\,\,\begin{array}{|c||c|}
 & M^{L^{A}}\\
\hline \bbnum 1 & 1\rightarrow\text{Nil}\triangleright\text{pu}_{M}\\
A\times M^{L^{A}} & a\times m\rightarrow\text{comb}\,(a\triangleright\text{pu}_{T})(m\triangleright\overline{\text{pu}}_{T}^{\uparrow L\uparrow M}\bef\overline{\text{prod}}^{\uparrow M}\bef\text{ftn}_{M})
\end{array}\quad.
\end{align*}
Simplify the second row of the matrix separately:
\begin{align*}
 & \text{comb}\,(a\triangleright\text{pu}_{T})(m\triangleright\gunderline{\overline{\text{pu}}_{T}^{\uparrow L\uparrow M}\bef\overline{\text{prod}}^{\uparrow M}}\bef\text{ftn}_{M})\\
{\color{greenunder}\text{inductive assumption}:}\quad & =\text{comb}\,(a\triangleright\text{pu}_{T})(m\triangleright\gunderline{\text{pu}_{M}\bef\text{ftn}_{M}})=\text{comb}\,(a\triangleright\text{pu}_{T})(m)\\
{\color{greenunder}\text{definition of }\text{comb}:}\quad & =a\triangleright\text{pu}_{L}\bef\gunderline{\text{pu}_{M}\bef\text{flm}_{M}}\bigg(\,\begin{array}{||c|}
1\rightarrow m\\
a\times p\rightarrow\text{pu}_{M}\big(\bbnum 0+a\times\overline{\text{comb}}\,(p)(m)\big)
\end{array}\,\bigg)\\
{\color{greenunder}\text{identity law of }M:}\quad & =\gunderline{a\triangleright\text{pu}_{L}}\triangleright\,\begin{array}{||c|}
1\rightarrow m\\
a\times p\rightarrow\text{pu}_{M}\big(\bbnum 0+a\times\overline{\text{comb}}\,(p)(m)\big)
\end{array}\\
{\color{greenunder}\text{definition of }\text{pu}_{L}:}\quad & =\,\begin{array}{||cc|}
\bbnum 0 & a\times(\text{Nil}\triangleright\text{pu}_{M})\end{array}\,\triangleright\,\begin{array}{||c|}
1\rightarrow m\\
a\times p\rightarrow\text{pu}_{M}\big(\bbnum 0+a\times\overline{\text{comb}}\,(p)(m)\big)
\end{array}\\
{\color{greenunder}\text{apply matrix}:}\quad & =\text{pu}_{M}\big(\bbnum 0+a\times\overline{\text{comb}}\,(p)(\text{Nil}\triangleright\text{pu}_{M})\big)=\text{pu}_{M}(\bbnum 0+a\times m)\quad.
\end{align*}
So, we find that the code matrix for $\text{pu}_{T}^{\uparrow L}\bef\text{prod}$
is
\begin{align*}
 & \text{pu}_{T}^{\uparrow L}\bef\text{prod}=\,\begin{array}{|c||c|}
 & M^{L^{A}}\\
\hline \bbnum 1 & 1\rightarrow\text{Nil}\triangleright\text{pu}_{M}\\
A\times M^{L^{A}} & a\times m\rightarrow\text{pu}_{M}(\bbnum 0+a\times m)
\end{array}\,=\,\begin{array}{|c||c|}
 & M^{L^{A}}\\
\hline \bbnum 1 & 1\rightarrow\text{pu}_{M}(1+\bbnum 0)\\
A\times M^{L^{A}} & a\times m\rightarrow\text{pu}_{M}(\bbnum 0+a\times m)
\end{array}\\
 & =\,\begin{array}{|c||c|}
 & \bbnum 1+A\times M^{L^{A}}\\
\hline \bbnum 1 & 1\rightarrow(1+\bbnum 0)\\
A\times M^{L^{A}} & a\times m\rightarrow(\bbnum 0+a\times m)
\end{array}\,\bef\text{pu}_{M}=\text{id}\bef\text{pu}_{M}=\text{pu}_{M}\quad.
\end{align*}
This proves the right identity law.

To verify the associativity law, write its two sides separately. We
will use the formula $\text{ftn}_{T}=\text{prod}^{\uparrow M}\bef\text{ftn}_{M}$
to make the derivation shorter, but we will not use any laws of $\text{ftn}_{T}$
in the derivation (since those laws will be established only after
this proof is complete).

Some useful properties are:
\begin{align*}
 & \text{Nil}\triangleright\text{prod}=\text{Nil}\triangleright\text{pu}_{M}\quad,\\
 & \text{pu}_{M}\bef\text{ftn}_{T}=\gunderline{\text{pu}_{M}\bef\text{prod}^{\uparrow M}}\bef\text{ftn}_{M}=\text{prod}\bef\gunderline{\text{pu}_{M}\bef\text{ftn}_{M}}=\text{prod}\quad.
\end{align*}

Begin with the left-hand side of the associativity law:
\begin{align*}
 & \text{prod}\bef\gunderline{\text{prod}^{\uparrow M}\bef\text{ftn}_{M}}=\text{prod}\bef\text{ftn}_{T}=\,\begin{array}{||c|}
1\rightarrow\text{Nil}\triangleright\gunderline{\text{pu}_{M}\bef\text{ftn}_{T}}\\
m\times p\rightarrow\text{comb}\,(m)(p\triangleright\overline{\text{prod}}^{\uparrow M}\bef\text{ftn}_{M})\,\gunderline{\triangleright\text{ftn}_{T}}
\end{array}\\
 & =\,\begin{array}{||c|}
1\rightarrow\gunderline{\text{Nil}\triangleright\text{prod}}\\
m\times p\rightarrow\text{comb}\,(m\triangleright\text{ftn}_{T})(p\triangleright\gunderline{\overline{\text{prod}}^{\uparrow M}\bef\text{ftn}_{M}}\bef\text{ftn}_{T})
\end{array}\\
 & =\,\,\begin{array}{||c|}
1\rightarrow\text{Nil}\triangleright\text{pu}_{M}\\
m\times p\rightarrow\text{comb}\,(m\triangleright\text{ftn}_{T})(p\triangleright\overline{\text{ftn}}_{T}\bef\text{ftn}_{T})
\end{array}\quad.
\end{align*}
To transform the right-hand side of the associativity law, we need
the lifting to $L$:
\[
\text{prod}^{\uparrow M\uparrow L}\bef\text{ftn}_{M}^{\uparrow L}=\text{ftn}_{T}^{\uparrow L}=\,\begin{array}{|c||cc|}
 & \bbnum 1 & T^{A}\times T^{T^{A}}\\
\hline \bbnum 1 & \text{id} & \bbnum 0\\
T^{T^{A}}\times T^{T^{T^{A}}} & \bbnum 0 & h\times t\rightarrow(h\triangleright\text{ftn}_{T})\times(t\triangleright\text{ftn}_{T}^{\overline{\uparrow L}\uparrow M})
\end{array}\quad.
\]
Then the right-hand side is written as
\begin{align*}
 & \text{prod}^{\uparrow M\uparrow L}\bef\text{ftn}_{M}^{\uparrow L}\bef\text{prod}=\text{ftn}_{T}^{\uparrow L}\bef\text{prod}\\
 & =\,\begin{array}{||cc|}
\text{id} & \bbnum 0\\
\bbnum 0 & h\times t\rightarrow(h\triangleright\text{ftn}_{T})\times(t\triangleright\text{ftn}_{T}^{\overline{\uparrow L}\uparrow M})
\end{array}\,\bef\,\begin{array}{||c|}
1\rightarrow\text{Nil}\triangleright\text{pu}_{M}\\
m\times p\rightarrow\text{comb}\,(m)(p\triangleright\overline{\text{ftn}}_{T})
\end{array}\\
 & =\,\,\begin{array}{||c|}
1\rightarrow\text{Nil}\triangleright\text{pu}_{M}\\
h\times t\rightarrow\text{comb}\,(h\triangleright\text{ftn}_{T})(t\triangleright\text{ftn}_{T}^{\overline{\uparrow L}\uparrow M}\triangleright\overline{\text{ftn}}_{T})
\end{array}\quad.
\end{align*}
The two matrices differ only in the last rows. We rename $m$, $p$
to $h$, $t$ and get 
\[
\text{comb}\,(h\triangleright\text{ftn}_{T})(t\triangleright\overline{\text{ftn}}_{T}\bef\text{ftn}_{T})\overset{?}{=}\text{comb}\,(h\triangleright\text{ftn}_{T})(t\triangleright\text{ftn}_{T}^{\overline{\uparrow L}\uparrow M}\triangleright\overline{\text{ftn}}_{T})\quad.
\]
The remaining difference is
\[
\overline{\text{ftn}}_{T}\bef\text{ftn}_{T}\overset{?}{=}\text{ftn}_{T}^{\overline{\uparrow L}\uparrow M}\bef\overline{\text{ftn}}_{T}\quad.
\]
This looks like the associativity law for $\text{ftn}_{T}$ applied
to some recursive calls to $\text{ftn}_{T}$ (note that $f^{\uparrow L\uparrow M}=f^{\uparrow T}$
by definition of $T\triangleq M\circ L$). However, here we may \emph{not}
assume that the associativity law holds for $\text{ftn}_{T}$. The
only allowed inductive hypothesis is that the law~(\ref{eq:associativity-law-of-prod-for-effectful-list})
holds when it involves any recursive calls to \lstinline!prod!. So,
we need to rewrite the above equation through $\overline{\text{prod}}$:
\begin{align*}
{\color{greenunder}\text{left-hand side}:}\quad & \overline{\text{ftn}}_{T}\bef\text{ftn}_{T}=\text{flm}_{M}(\overline{\text{prod}})\bef\text{flm}_{M}(\text{prod})\\
{\color{greenunder}\text{associativity law of }\text{flm}_{M}:}\quad & \quad=\text{flm}_{M}(\overline{\text{prod}}\bef\text{flm}_{M}(\text{prod}))\\
{\color{greenunder}\text{right-hand side}:}\quad & \overset{?}{=}\text{ftn}_{T}^{\overline{\uparrow L}\uparrow M}\bef\overline{\text{ftn}}_{T}=\text{ftn}_{T}^{\overline{\uparrow L}\uparrow M}\bef\text{flm}_{M}(\overline{\text{prod}})\\
{\color{greenunder}\text{naturality law of }\text{flm}_{M}:}\quad & \quad=\text{flm}_{M}(\text{ftn}_{T}^{\overline{\uparrow L}}\bef\overline{\text{prod}})=\text{flm}_{M}(\text{ftn}_{T}^{\overline{\uparrow L}}\bef\overline{\text{prod}})\quad.
\end{align*}
It remains to show that
\[
\overline{\text{prod}}\bef\text{flm}_{M}(\text{prod})=\overline{\text{prod}}\bef\text{prod}^{\uparrow M}\bef\text{ftn}_{M}\overset{?}{=}\text{ftn}_{T}^{\overline{\uparrow L}}\bef\overline{\text{prod}}=(\text{prod}^{\uparrow M}\bef\text{ftn}_{M})^{\uparrow L}\bef\overline{\text{prod}}\quad.
\]
This is equivalent to
\[
\overline{\text{prod}}\bef\text{prod}^{\uparrow M}\bef\text{ftn}_{M}\overset{?}{=}\text{prod}^{\uparrow M\uparrow L}\bef\text{ftn}_{M}^{\uparrow L}\bef\overline{\text{prod}}\quad,
\]
which holds by the inductive assumption. So, the associativity law
of \lstinline!prod! holds.

To verify the monadic naturality law of \lstinline!prod!, begin with
its left-hand side:
\begin{align*}
 & \text{prod}_{M,L}\bef\psi^{\uparrow M}\bef\phi=\,\begin{array}{||c|}
1\rightarrow\text{Nil}\triangleright\gunderline{\text{pu}_{M}\bef\psi^{\uparrow M}}\bef\phi\\
h\times t\rightarrow\text{comb}\,(h)(t\triangleright\overline{\text{ftn}}_{T})\triangleright\psi^{\uparrow M}\bef\phi
\end{array}\\
 & =\,\begin{array}{||c|}
1\rightarrow\gunderline{\text{Nil}\triangleright\psi}\bef\gunderline{\text{pu}_{M}\bef\phi}\\
h\times t\rightarrow\text{comb}\,(h)(t\triangleright\overline{\text{ftn}}_{T})\triangleright\psi^{\uparrow M}\bef\phi
\end{array}\,=\,\begin{array}{||c|}
1\rightarrow\text{Nil}\triangleright\text{pu}_{M^{\prime}}\\
h\times t\rightarrow\text{comb}\,(h)(t\triangleright\overline{\text{ftn}}_{T})\triangleright\psi^{\uparrow M}\bef\phi
\end{array}\quad.
\end{align*}
For the right-hand side of the monadic naturality law, we simplify
the expression $\psi\bef\text{prod}$ separately:
\begin{align*}
 & \psi\bef\text{prod}_{M^{\prime},L^{\prime}}=\,\begin{array}{||cc|}
\text{id} & \bbnum 0\\
\bbnum 0 & h\times t\rightarrow h\times(t\triangleright\psi^{\uparrow M}\bef\phi)
\end{array}\,\bef\,\begin{array}{|c||c|}
 & M^{\prime L^{\prime A}}\\
\hline \bbnum 1 & 1\rightarrow\text{Nil}\triangleright\text{pu}_{M^{\prime}}\\
M^{\prime L^{\prime A}}\times M^{\prime L^{\prime M^{\prime L^{\prime A}}}} & m\times p\rightarrow\text{comb}\,(m)(p\triangleright\overline{\text{ftn}}_{T^{\prime}})
\end{array}\\
 & =\,\begin{array}{||c|}
1\rightarrow\text{Nil}\triangleright\text{pu}_{M^{\prime}}\\
h\times t\rightarrow\text{comb}\,(h)(t\triangleright\psi^{\uparrow M}\bef\phi\bef\overline{\text{ftn}}_{T^{\prime}})
\end{array}\quad.
\end{align*}
Now the right-hand side of the law can be written as
\begin{align*}
 & (\psi^{\uparrow M}\bef\phi)^{\uparrow L}\bef\psi\bef\text{prod}_{M^{\prime},L^{\prime}}\\
 & =\,\begin{array}{||cc|}
\text{id} & \bbnum 0\\
\bbnum 0 & h\times t\rightarrow(h\triangleright\psi^{\uparrow M}\bef\phi)\times\big(t\triangleright(\psi^{\uparrow M}\bef\phi)^{\overline{\uparrow L}\uparrow M}\big)
\end{array}\,\bef\,\begin{array}{||c|}
1\rightarrow\text{Nil}\triangleright\text{pu}_{M^{\prime}}\\
h\times t\rightarrow\text{comb}\,(h)(t\triangleright\psi^{\uparrow M}\bef\phi\bef\overline{\text{ftn}}_{T^{\prime}})
\end{array}\\
 & =\,\,\begin{array}{||c|}
1\rightarrow\text{Nil}\triangleright\text{pu}_{M^{\prime}}\\
h\times t\rightarrow\text{comb}\,(h\triangleright\psi^{\uparrow M}\bef\phi)\big(t\triangleright(\psi^{\uparrow M}\bef\phi)^{\overline{\uparrow L}\uparrow M}\bef\psi^{\uparrow M}\bef\phi\bef\overline{\text{ftn}}_{T^{\prime}}\big)
\end{array}\quad.
\end{align*}
The difference between the two sides is now only in the last rows
of the matrices:
\[
\text{comb}\,(h)(t\triangleright\overline{\text{ftn}}_{T})\triangleright\psi^{\uparrow M}\bef\phi\overset{?}{=}\text{comb}\,(h\triangleright\psi^{\uparrow M}\bef\phi)\big(t\triangleright(\psi^{\uparrow M}\bef\phi)^{\overline{\uparrow L}\uparrow M}\bef\psi^{\uparrow M}\bef\phi\bef\overline{\text{ftn}}_{T^{\prime}}\big)\quad.
\]
By Statement~\ref{subsec:Statement-monadic-naturality-of-comb-for-effectful-list},
we have:
\[
\text{comb}\,(h)(t\triangleright\overline{\text{ftn}}_{T})\triangleright\psi^{\uparrow M}\bef\phi=\text{comb}\,(h\triangleright\psi^{\uparrow M}\bef\phi)(t\triangleright\overline{\text{ftn}}_{T}\bef\psi^{\uparrow M}\bef\phi)\quad.
\]
The remaining difference between the two sides is
\[
(\psi^{\uparrow M}\bef\phi)^{\overline{\uparrow L}\uparrow M}\bef\psi^{\uparrow M}\bef\phi\bef\overline{\text{ftn}}_{T^{\prime}}\overset{?}{=}\overline{\text{ftn}}_{T}\bef\psi^{\uparrow M}\bef\phi\quad.
\]
This is the monad morphism composition law for $\text{frun}\,(\phi)\triangleq\psi^{\uparrow M}\bef\phi$.
However, the present proof must be completed without assuming that
\lstinline!frun! is a monad morphism (of type $T\leadsto T^{\prime}$).

So, we need to replace $\text{ftn}_{T}$ with \lstinline!prod! in
both sides above:
\begin{align*}
{\color{greenunder}\text{left-hand side}:}\quad & (\psi^{\uparrow M}\bef\phi)^{\overline{\uparrow L}\uparrow M}\bef\psi^{\uparrow M}\bef\phi\bef\overline{\text{ftn}}_{T^{\prime}}=\gunderline{(\psi^{\uparrow M}\bef\phi)^{\overline{\uparrow L}\uparrow M}\bef\psi^{\uparrow M}\bef\phi}\bef\text{flm}_{M^{\prime}}(\overline{\text{prod}})\\
{\color{greenunder}\text{naturality law of }\phi:}\quad & \quad=\phi\bef\big((\psi^{\uparrow M}\bef\phi)^{\overline{\uparrow L}}\bef\psi\big)^{\uparrow M^{\prime}}\bef\text{flm}_{M^{\prime}}(\overline{\text{prod}})\\
{\color{greenunder}\text{naturality law of }\text{flm}_{M}:}\quad & \quad=\phi\bef\text{flm}_{M^{\prime}}((\psi^{\uparrow M}\bef\phi)^{\overline{\uparrow L}}\bef\psi\bef\overline{\text{prod}})\quad,\\
{\color{greenunder}\text{right-hand side}:}\quad & \overline{\text{ftn}}_{T}\bef\psi^{\uparrow M}\bef\phi=\text{flm}_{M}(\overline{\text{prod}})\bef\psi^{\uparrow M}\bef\phi\\
{\color{greenunder}\text{naturality law of }\text{flm}_{M}:}\quad & \quad=\text{flm}_{M}(\overline{\text{prod}}\bef\psi^{\uparrow M})\bef\phi\\
{\color{greenunder}\text{composition law of }\phi:}\quad & \quad=\phi\bef\text{flm}_{M^{\prime}}(\overline{\text{prod}}\bef\psi^{\uparrow M}\bef\phi)\quad.
\end{align*}
It is clear that we need to use the inductive hypothesis to make progress.
We adapt the inductive hypothesis to be used in the above equation:
\begin{align*}
{\color{greenunder}\text{inductive hypothesis}:}\quad & \overline{\text{prod}}_{M,L}\bef\psi^{\uparrow M}\bef\phi=(\psi^{\uparrow M}\bef\phi)^{\uparrow L}\bef\psi\bef\overline{\text{prod}}_{M^{\prime},L^{\prime}}\quad,\\
{\color{greenunder}\text{apply }\text{flm}_{M^{\prime}}\text{ to both sides}:}\quad & \text{flm}_{M^{\prime}}\big(\overline{\text{prod}}_{M,L}\bef\psi^{\uparrow M}\bef\phi\big)=\text{flm}_{M^{\prime}}\big((\psi^{\uparrow M}\bef\phi)^{\uparrow L}\bef\psi\bef\overline{\text{prod}}_{M^{\prime},L^{\prime}}\big)\quad.
\end{align*}
Now we can rewrite both sides to obtain the following expressions:
\begin{align*}
{\color{greenunder}\text{left-hand side}:}\quad & (\psi^{\uparrow M}\bef\phi)^{\overline{\uparrow L}\uparrow M}\bef\psi^{\uparrow M}\bef\phi\bef\overline{\text{ftn}}_{T^{\prime}}=\phi\bef\text{flm}_{M^{\prime}}((\psi^{\uparrow M}\bef\phi)^{\overline{\uparrow L}}\bef\psi\bef\overline{\text{prod}})\\
{\color{greenunder}\text{right-hand side}:}\quad & \overset{?}{=}\overline{\text{ftn}}_{T}\bef\psi^{\uparrow M}\bef\phi=\phi\bef\text{flm}_{M^{\prime}}\big((\psi^{\uparrow M}\bef\phi)^{\uparrow L}\bef\psi\bef\overline{\text{prod}}_{M^{\prime},L^{\prime}}\big)\quad.
\end{align*}
Both sides are now equal.

This completes the proof of the laws for the \lstinline!List! monad
transformer.

\section{Incomplete transformers}

A \textbf{complete}\index{monad transformers!completeness} monad
transformer must fully conform to the laws of a pointed and co-pointed
functor in the category of monads (see Section~\ref{subsec:Category-theoretic-properties-of-lifts-and-runners-functors-in-category-of-monads}).
These laws guarantee the existence of general forms of lifts and runners.
The monad transformers for linear monads, rigid monads, product monads,
free pointed monads, and recursive (tree-like and list-like) monads
are \textsf{``}complete\textsf{''}, as we have proved in the previous sections. We
now consider certain monads (state, continuation, choice, and codensity)
whose transformers are incomplete. Those transformers are deficient
in one or another way, and they do not correspond to lawful pointed
and co-pointed functors in the category of monads. This leads to certain
limitations in the practical use of the affected transformers.

\subsection{Transformer for the state monad. Proofs}

The transformer for the \lstinline!State! monad is not compositional;
as shown in Examples~\ref{subsec:Example-state-monad-composition-fails-with-option}\textendash \ref{subsec:Example-state-monad-composition-fails-with-reader},
the \lstinline!State! monad does not compose with arbitrary other
monads. Instead, the transformer needs a custom definition (Section~\ref{subsec:Monad-transformers-for-standard-monads}).

\subsubsection{Statement \label{subsec:Statement-state-monad-transformer}\ref{subsec:Statement-state-monad-transformer}}

The monad transformer (\lstinline!StateT!) for the \lstinline!State!
monad is 
\[
T_{\text{State}}^{M,A}\triangleq S\rightarrow M^{A\times S}\quad.
\]
It satisfies all monad transformer laws except for the monad morphism
laws for base runners.

\subparagraph{Proof}

We need to verify all the monad transformer laws (Section~\ref{subsec:Laws-of-monad-transformers})
separately.

As we will see below, the \lstinline!StateT! transformer has one
problem: its base runner violates the monad morphism composition law.
The standard runner for the \lstinline!State! monad,
\[
\text{run}_{\text{State}}(s_{0}):\text{State}^{S,A}\rightarrow A\quad,\quad\quad\text{run}_{\text{State}}(s_{0})\triangleq p^{:S\rightarrow A\times S}\rightarrow p(s_{0})\triangleright\pi_{1}\quad,
\]
also violates that law because it discards the updated state, while
the composition law requires to pass the updated state to the next
monad value. For the \lstinline!State! monad, this problem can be
solved by starting the runner from an updated intermediate state instead
of the fixed initial state $s_{0}$. However, that trick cannot be
used with the \lstinline!StateT! transformer whose updated state
is wrapped as $M^{A\times S}$ in an arbitrary foreign monad $M$.
The monad $M$\textsf{'}s effect could wrap several values, or no values at
all. The \textsf{``}updated intermediate state\textsf{''} is not well-defined in that
case.

For this reason, a monadic program involving \lstinline!StateT! cannot
be refactored to run in several steps. To get correct results, the
runner must be applied to the entire monadic program.

In the language of category theory, the \lstinline!StateT! transformer
fails to be a co-pointed functor in the category of monads. However,
it is a pointed functor in that category: its lifts and the foreign
runner satisfy all laws, as we will prove shortly.

\paragraph{Monad laws}

We need to show that $T_{\text{State}}^{M}$ is a lawful monad, assuming
that $M$ is one. The monad methods for $T_{\text{State}}^{M}$ are
defined by Eqs.~(\ref{eq:pure-for-stateT-transformer})\textendash (\ref{eq:flatmap-for-stateT-transformer}).
To verify the monad laws, it is faster to use the uncurried Kleisli
formulation, as we did for the \lstinline!State! monad (Statement~\ref{subsec:Statement-state-monad-is-lawful}). 

The type signature for a $T_{\text{State}}$-Kleisli function is 
\[
A\rightarrow T_{\text{State}}^{M,B}=A\rightarrow S\rightarrow M^{B\times S}\quad.
\]
When we uncurry this type signature, we get the type $A\times S\rightarrow M^{B\times S}$.
It is easy to define the Kleisli composition ($\tilde{\diamond}_{_{T}}$)
for uncurried Kleisli functions because $\tilde{\diamond}_{_{T}}$
is the same as the $M$-Kleisli composition ($\diamond_{_{M}}$) except
applied to types $A\times S$, $B\times S$, and $C\times S$:
\[
f^{:A\times S\rightarrow M^{B\times S}}\,\tilde{\diamond}_{_{T}}\,g^{:B\times S\rightarrow M^{C\times S}}\triangleq f\diamond_{_{M}}g\quad.
\]
The proper $T_{\text{State}}$-Kleisli composition ($\diamond_{_{T}}$)
is then defined by
\[
f^{:A\rightarrow S\rightarrow M^{B\times S}}\diamond_{_{T}}g^{:B\rightarrow S\rightarrow M^{C\times S}}\triangleq\text{uncu}\left(f\right)\diamond_{_{M}}\text{uncu}\left(g\right)\quad.
\]
The \textbf{uncurrying}\index{uncurrying} transformation 
\[
\text{uncu}:\left(A\rightarrow B\rightarrow C\right)\rightarrow A\times B\rightarrow C\quad,\quad\quad\text{uncu}\left(f\right)\triangleq a^{:A}\times b^{:B}\rightarrow f(a)(b)\quad,
\]
is an isomorphism with the inverse (\textbf{currying}\index{currying})
transformation
\[
\text{cu}:\left(A\times B\rightarrow C\right)\rightarrow A\rightarrow B\rightarrow C\quad,\quad\quad\text{cu}\left(f\right)\triangleq a^{:A}\rightarrow b^{:B}\rightarrow f(a\times b)\quad.
\]
So, it is sufficient to verify the monad laws in the uncurried Kleisli
formulation. 

To verify the identity laws, we need to define the uncurried \lstinline!pure!
method for $T_{\text{State}}$:
\[
\tilde{\text{pu}}_{T}\triangleq\text{uncu}\,(\text{pu}_{T})=a^{:A}\times s^{:S}\rightarrow\text{pu}_{M}(a\times s)=\text{pu}_{M}^{A\times S}\quad.
\]
It is now quick to show that all three monad laws for $T_{\text{State}}$
hold due to $M$\textsf{'}s monad laws:
\begin{align*}
\tilde{\text{pu}}_{T}\,\tilde{\diamond}_{_{T}}\,f=\text{pu}_{M}\diamond_{_{M}}f=f\quad, & \quad\quad f\,\tilde{\diamond}_{_{T}}\,\tilde{\text{pu}}_{T}=f\diamond_{_{M}}\text{pu}_{M}=f\quad,\\
(f\,\tilde{\diamond}_{_{T}}\,g)\,\tilde{\diamond}_{_{T}}\,h=(f\diamond_{_{M}}g)\diamond_{_{M}}h & =f\diamond_{_{M}}(g\diamond_{_{M}}h)=f\,\tilde{\diamond}_{_{T}}\,(g\,\tilde{\diamond}_{_{T}}\,h)\quad.
\end{align*}


\paragraph{Identity laws}

When $M=\text{Id}$, the type of $T_{\text{State}}^{M,A}$ becomes
equal to $\text{State}^{A}$, and the monad methods become equal to
those of the \lstinline!State! monad.

\paragraph{Lifting laws}

The \lstinline!flift! function is defined by
\begin{equation}
m^{:M^{A}}\triangleright\text{flift}\triangleq s^{:S}\rightarrow m\triangleright(a^{:A}\rightarrow a\times s)^{\uparrow M}\quad.\label{eq:state-transformer-def-of-flift}
\end{equation}
We need to show that \lstinline!flift! is a monad morphism $M\leadsto T_{\text{State}}^{M}$.
The identity law:
\begin{align*}
 & a^{:A}\triangleright\text{pu}_{M}\triangleright\text{flift}=s\rightarrow a\triangleright\gunderline{\text{pu}_{M}\bef(a^{:A}\rightarrow a\times s)^{\uparrow M}}\\
{\color{greenunder}\text{naturality law of }\text{pu}_{M}:}\quad & =s\rightarrow a\triangleright(a^{:A}\rightarrow a\times s)\bef\text{pu}_{M}=s\rightarrow\text{pu}_{M}(a\times s)=\text{pu}_{T}\quad.
\end{align*}

The composition law in terms of the Kleisli composition ($\diamond_{_{T}}$)
is:
\[
(f^{:A\rightarrow M^{B}}\bef\text{flift})\diamond_{_{T}}\!(g^{:B\rightarrow M^{C}}\bef\text{flift})\overset{?}{=}(f\diamond_{_{M}}g)\bef\text{flift}\quad.
\]
In terms of $\tilde{\diamond}_{_{T}}$, this equation is reformulated
as
\[
\text{uncu}\,(f^{:A\rightarrow M^{B}}\bef\text{flift})\,\tilde{\diamond}_{_{T}}\text{uncu}\,(g^{:B\rightarrow M^{C}}\bef\text{flift})\overset{?}{=}\text{uncu}\,\big((f\diamond_{_{M}}g)\bef\text{flift}\big)\quad.
\]
To show that this equation holds, begin by uncurrying the arguments
of $\diamond_{_{T}}$:
\begin{align*}
 & \text{uncu}\,(f^{:A\rightarrow M^{B}}\bef\text{flift})=\text{uncu}\,(a^{:A}\rightarrow f(a)\triangleright\text{flift})=\text{uncu}\,\big(a^{:A}\rightarrow s^{:S}\rightarrow a\triangleright f\triangleright(b^{:B}\rightarrow b\times s)^{\uparrow M}\big)\\
 & =a\times s\rightarrow a\triangleright f\bef(b\rightarrow b\times s)^{\uparrow M}\quad.
\end{align*}
Using this formula, we get:
\begin{align*}
 & \text{uncu}\,(f^{:A\rightarrow M^{B}}\bef\text{flift})\,\tilde{\diamond}_{_{T}}\,\text{uncu}\,(g^{:B\rightarrow M^{C}}\bef\text{flift})=\text{uncu}\,(f^{:A\rightarrow M^{B}}\bef\text{flift})\diamond_{_{M}}\text{uncu}\,(g^{:B\rightarrow M^{C}}\bef\text{flift})\\
 & =\big(a\times s\rightarrow a\triangleright f\bef(b\rightarrow b\times s)^{\uparrow M}\big)\diamond_{_{M}}\big(b\times s\rightarrow b\triangleright g\bef(c\rightarrow c\times s)^{\uparrow M}\big)\quad.
\end{align*}
We need somehow to move $(b\rightarrow b\times s)^{\uparrow M}$ to
the right of $\diamond_{_{M}}$. However, the naturality law of $\diamond_{_{M}}$
cannot be applied because $(b\rightarrow b\times s)^{\uparrow M}$
contains the variable $s$, which is bound in the scope of the left
argument of $\diamond_{_{M}}$. To proceed, let us apply the expression
to an arbitrary value $a\times s$, which will enable us to move the
rest of the expression ($\diamond_{_{M}}...$) into the scope of the
left argument of $\diamond_{_{M}}$:
\begin{align*}
 & \left(a\times s\right)\triangleright\big(a\times s\rightarrow a\triangleright f\bef(b\rightarrow b\times s)^{\uparrow M}\big)\diamond_{_{M}}...\\
 & =\left(a\times s\right)\triangleright\big(a\times s\rightarrow a\triangleright f\bef(b\rightarrow b\times s)^{\uparrow M}\big)\bef\text{flm}_{M}(...)\\
 & =a\triangleright f\bef(b\rightarrow b\times s)^{\uparrow M}\bef\text{flm}_{M}(...)=a\triangleright f\bef(b\rightarrow b\times s)^{\uparrow M}\diamond_{_{M}}...
\end{align*}
This trick allows us to complete the derivation:
\begin{align*}
 & a\triangleright f\bef(b\rightarrow b\times s)^{\uparrow M}\diamond_{_{M}}\big(b\times s\rightarrow b\triangleright g\bef(c\rightarrow c\times s)^{\uparrow M}\big)\\
{\color{greenunder}\text{naturality law of }\diamond_{_{M}}:}\quad & =a\triangleright f\diamond_{_{M}}(b\rightarrow\gunderline{b\times s)\bef\big(b\times s}\rightarrow b\triangleright g\bef(c\rightarrow c\times s)^{\uparrow M}\big)\\
{\color{greenunder}\text{compute composition}:}\quad & =a\triangleright f\diamond_{_{M}}\big(\gunderline{b\rightarrow b\,\triangleright}\,g\bef(c\rightarrow c\times s)^{\uparrow M}\big)\\
{\color{greenunder}\triangleright\text{-notation}:}\quad & =a\triangleright f\diamond_{_{M}}(g\bef\gunderline{(c\rightarrow c\times s)^{\uparrow M}})\\
{\color{greenunder}\text{naturality law of }\diamond_{_{M}}:}\quad & =a\triangleright(f\diamond_{_{M}}g)\bef(c\rightarrow c\times s)^{\uparrow M}=\left(a\times s\right)\triangleright\text{uncu}\,\big((f\diamond_{_{M}}g)\bef\text{flift}\big)\quad.
\end{align*}
 

\paragraph{Foreign runner laws}

The foreign runner (\lstinline!frun!) is defined by
\[
\text{frun}\,(\phi^{:M\leadsto N})\triangleq p^{:S\rightarrow M^{A\times S}}\rightarrow\gunderline{s^{:S}\rightarrow s\,\triangleright}\,p\triangleright\phi=p^{:S\rightarrow M^{A\times S}}\rightarrow p\bef\phi\quad.
\]

First, we need to prove that $\text{frun}\left(\phi\right)$ is a
monad morphism of type $T_{\text{State}}^{M}\leadsto T_{\text{State}}^{N}$.
For convenience, denote $P\triangleq T_{\text{State}}^{M}$ and $Q\triangleq T_{\text{State}}^{N}$.
To verify the identity law:
\begin{align*}
 & \text{pu}_{P}\bef\text{frun}\,(\phi^{:M\leadsto N})=(a^{:A}\rightarrow s^{:S}\rightarrow(a\times s)\triangleright\text{pu}_{M})\bef(p\rightarrow p\bef\phi)\\
{\color{greenunder}\text{compute composition}:}\quad & =a\rightarrow s\rightarrow(a\times s)\triangleright\gunderline{\text{pu}_{M}\bef\phi}\\
{\color{greenunder}\text{identity law of }\phi:}\quad & =a\rightarrow s\rightarrow(a\times s)\triangleright\text{pu}_{N}=\text{pu}_{Q}\quad.
\end{align*}
The composition law is easier to verify in the uncurried Kleisli formulation.
For brevity, denote $r\triangleq\text{frun}\left(\phi\right)$; this
is a monad morphism of type $P\leadsto Q$. We need to show that
\[
\big(f^{:A\rightarrow P^{B}}\bef r\big)\diamond_{_{Q}}(g^{:B\rightarrow P^{C}}\bef r)\overset{?}{=}(f\diamond_{_{P}}g)\bef r\quad.
\]
Express this through uncurried functions and the operations $\diamond_{_{P}}$
and $\tilde{\diamond}_{_{Q}}$:
\[
\text{uncu}\,\big(f^{:A\rightarrow P^{B}}\bef r\big)\,\tilde{\diamond}_{_{Q}}\,\text{uncu}\,(g^{:B\rightarrow P^{C}}\bef r)\overset{?}{=}\text{uncu}\,\big((f\diamond_{_{P}}g)\bef r\big)\quad.
\]
Uncurrying a function composition such as $f\bef r$ works like this:
\begin{align}
 & \text{uncu}\,\big(f^{:A\rightarrow S\rightarrow M^{B\times S}}\bef r^{:P^{B}\leadsto Q^{B}}\big)=a^{:A}\times s^{:S}\rightarrow s\triangleright(\gunderline{a\triangleright f\bef r})=a^{:A}\times s^{:S}\rightarrow s\triangleright(f(a)\triangleright\gunderline r)\nonumber \\
{\color{greenunder}\text{definition of }r:}\quad & =a\times s\rightarrow s\triangleright(\gunderline{f(a)\triangleright(p\rightarrow p\bef\phi)})=a\times s\rightarrow s\triangleright f(a)\bef\phi\nonumber \\
 & =\big(a\times s\rightarrow s\triangleright f(a)\big)\bef\phi=\text{uncu}\,(f)\bef\phi\quad.\label{eq:uncurry-state-composition-derivation1}
\end{align}
The right-hand side of the composition law then becomes:
\[
\text{uncu}\,\big((f\diamond_{_{P}}g)\bef r\big)=\text{uncu}\,(f\diamond_{_{P}}g)\bef\phi=\big(\text{uncu}\left(f\right)\diamond_{_{M}}\text{uncu}\left(g\right)\big)\bef\phi\quad.
\]
We can now proceed to simplify the left-hand side of the composition
law:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{uncu}\,\big((f\diamond_{_{P}}g)\bef r\big):}\quad & \gunderline{\text{uncu}\,\big(f^{:A\rightarrow P^{B}}\bef r\big)}\,\tilde{\diamond}_{_{Q}}\,\gunderline{\text{uncu}\,(g^{:B\rightarrow P^{C}}\bef r)}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:uncurry-state-composition-derivation1})}:}\quad & =\big(\text{uncu}\left(f\right)\bef\phi\big)\,\gunderline{\tilde{\diamond}_{_{Q}}}\,\big(\text{uncu}\left(g\right)\bef\phi\big)\\
{\color{greenunder}\text{definition of }\tilde{\diamond}_{_{Q}}:}\quad & =\big(\text{uncu}\left(f\right)\bef\phi\big)\diamond_{_{N}}\big(\text{uncu}\left(g\right)\bef\phi\big)\\
{\color{greenunder}\text{composition law of }\phi:}\quad & =\big(\text{uncu}\left(f\right)\diamond_{_{M}}\text{uncu}\left(g\right)\big)\bef\phi=\text{uncu}\,\big((f\diamond_{_{P}}g)\bef r\big)\quad.
\end{align*}

It remains to verify that $\text{frun}\,(\phi^{:M\leadsto N})$ satisfies
the functor laws with respect to the monad parameters $M$, $N$.
The functor identity law:
\[
\text{frun}\,(\text{id}^{:M\leadsto M})=p\rightarrow p\bef\text{id}=p\rightarrow p=\text{id}\quad.
\]
The functor composition law:
\[
\text{frun}\,(\phi^{:L\leadsto M})\bef\text{frun}\,(\chi^{:M\leadsto N})=(p\rightarrow p\bef\phi)\bef(q\rightarrow q\bef\chi)=p\rightarrow p\bef\phi\bef\chi=\text{frun}\,(\phi\bef\chi)\quad.
\]


\paragraph{Base runner laws}

The base runner is parameterized by an initial state value $s_{0}$:
\[
\text{brun}\,(s_{0})\triangleq p^{:S\rightarrow M^{A\times S}}\rightarrow p(s_{0})\triangleright\pi_{1}^{\uparrow M}\quad.
\]

We will check the laws for a fixed $s_{0}$. The non-degeneracy law
holds:
\begin{align*}
{\color{greenunder}\text{expect to equal }m:}\quad & m\triangleright\text{flift}\triangleright\text{brun}\,(s_{0})=m\triangleright\text{flift}\triangleright(p\rightarrow p(s_{0})\triangleright\pi_{1}^{\uparrow M})=s_{0}\triangleright(\gunderline{m\triangleright\text{flift}})\triangleright\pi_{1}^{\uparrow M}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:state-transformer-def-of-flift})}:}\quad & =m\triangleright(a\rightarrow a\times s_{0})^{\uparrow M}\triangleright\pi_{1}^{\uparrow M}=m\triangleright(a\rightarrow a)=m\quad.
\end{align*}

We now turn to the monadic morphism laws. The identity law holds:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{pu}_{M}:}\quad & \text{pu}_{P}\bef\text{brun}\,(s_{0})=\big(a\rightarrow s\rightarrow(a\times s)\triangleright\text{pu}_{M}\big)\bef(p\rightarrow p(s_{0})\triangleright\pi_{1}^{\uparrow M})\\
{\color{greenunder}\text{compute composition}:}\quad & =a\rightarrow(a\times s_{0})\triangleright\text{pu}_{M}\triangleright\pi_{1}^{\uparrow M}=a\rightarrow(a\times s_{0})\triangleright\gunderline{\text{pu}_{M}\bef\pi_{1}^{\uparrow M}}\\
{\color{greenunder}\text{naturality law of }\text{pu}_{M}:}\quad & =a\rightarrow(a\times s_{0})\triangleright\pi_{1}\bef\text{pu}_{M}=a\rightarrow a\triangleright\text{pu}_{M}=\text{pu}_{M}\quad.
\end{align*}

The composition law is quicker to check in the Kleisli formulation:
\[
\big(f^{:A\rightarrow S\rightarrow M^{B\times S}}\bef\text{brun}\,(s_{0})\big)\diamond_{_{M}}\big(g^{:B\rightarrow S\rightarrow M^{C\times S}}\bef\text{brun}\,(s_{0})\big)\overset{?}{=}(f\diamond_{_{P}}g)\bef\text{brun}\,(s_{0})\quad.
\]
Since it is easier to define $\diamond_{_{P}}$ in terms of the uncurried
Kleisli functions, let us express the composition $f\bef\text{brun}\,(s_{0})$
in terms of the uncurried version of $f$:
\begin{align}
 & f\bef\text{brun}\,(s_{0})=a\rightarrow a\triangleright f\triangleright(p\rightarrow p(s_{0})\triangleright\pi_{1}^{\uparrow M})=a\rightarrow f(a)(s_{0})\triangleright\pi_{1}^{\uparrow M}\nonumber \\
 & =a\rightarrow(a\times s_{0})\triangleright\text{uncu}\,(f)\bef\pi_{1}^{\uparrow M}=(a\rightarrow a\times s_{0})\bef\text{uncu}\,(f)\bef\pi_{1}^{\uparrow M}\quad.\label{eq:state-transformer-derivation2}
\end{align}
We can now write the left-hand side of the composition law as:
\begin{align*}
 & \big(f\bef\text{brun}\,(s_{0})\big)\diamond_{_{M}}\big(g\bef\text{brun}\,(s_{0})\big)=\big((a\rightarrow a\times s_{0})\bef\text{uncu}\,(f)\bef\gunderline{\pi_{1}^{\uparrow M}\big)\,\diamond_{_{M}}}\big(g\bef\text{brun}\,(s_{0})\big)\\
{\color{greenunder}\text{naturality of }\diamond_{_{M}}:}\quad & =(a\rightarrow a\times s_{0})\bef\text{uncu}\,(f)\diamond_{_{M}}\big(\pi_{1}\bef g\bef\text{brun}\,(s_{0})\big)\\
{\color{greenunder}\text{use Eq.~(\ref{eq:state-transformer-derivation2})}:}\quad & =(a\rightarrow a\times s_{0})\bef\text{uncu}\,(f)\diamond_{_{M}}\big(\pi_{1}\bef(b\rightarrow b\times s_{0})\bef\text{uncu}\,(g)\bef\pi_{1}^{\uparrow M}\big)\quad.
\end{align*}
The right-hand side of the law is:
\begin{align*}
 & (f\diamond_{_{P}}g)\bef\text{brun}\,(s_{0})=(a\rightarrow a\times s_{0})\bef\text{uncu}\,(f\diamond_{_{P}}g)\bef\pi_{1}^{\uparrow M}\\
{\color{greenunder}\text{definition of }\diamond_{_{P}}:}\quad & =(a\rightarrow a\times s_{0})\bef\big(\text{uncu}\,(f)\diamond_{_{M}}\text{uncu}\,(g)\gunderline{\big)\bef\pi_{1}^{\uparrow M}}\\
{\color{greenunder}\text{right naturality law of }\diamond_{_{M}}:}\quad & =(a\rightarrow a\times s_{0})\bef\text{uncu}\,(f)\diamond_{_{M}}\big(\text{uncu}\,(g)\bef\pi_{1}^{\uparrow M}\big)\quad.
\end{align*}
We find that the two sides of the law are \emph{not} equal. The difference
is the presence of a function $\pi_{1}\bef(b\rightarrow b\times s_{0})$
of type $B\times S\rightarrow B\times S$. That function replaces
the updated state by the fixed initial state $s_{0}$ before applying
the uncurried function $g$. This replacement erases the updated state,
which leads to an incorrect composition of effects in the \lstinline!StateT!
monad.

If we set $M=\text{Id}$, we will obtain the same violation for the
\lstinline!State! monad\textsf{'}s runner.

\paragraph{Monadic naturality laws}

To verify the monadic naturality of \lstinline!flift!, apply to an
arbitrary $m^{:M^{A}}$:
\begin{align*}
{\color{greenunder}\text{expect to equal }m\triangleright\phi\triangleright\text{flift}^{N}:}\quad & m\triangleright\text{flift}^{M}\triangleright\text{frun}\left(\phi\right)=m\triangleright\text{flift}^{M}\triangleright(p\rightarrow p\bef\phi)=(m\triangleright\text{flift}^{M})\bef\phi\\
{\color{greenunder}\text{use Eq.~(\ref{eq:state-transformer-def-of-flift})}:}\quad & =\big(s\rightarrow m\triangleright(a\rightarrow a\times s)^{\uparrow M}\big)\bef\phi=s\rightarrow m\triangleright\gunderline{(a\rightarrow a\times s)^{\uparrow M}\bef\phi}\\
{\color{greenunder}\text{naturality law of }\phi:}\quad & =s\rightarrow m\triangleright\phi\bef(a\rightarrow a\times s)^{\uparrow N}=m\triangleright\phi\triangleright\text{flift}^{N}\quad.
\end{align*}

To verify the monadic naturality of \lstinline!brun!:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{brun}\,(s_{0})\bef\phi:}\quad & \text{frun}\left(\phi\right)\bef\text{brun}\,(s_{0})=(p\rightarrow p\bef\phi)\bef(p\rightarrow s_{0}\triangleright p\bef\pi_{1}^{\uparrow N})\\
{\color{greenunder}\text{compute composition}:}\quad & =p\rightarrow s_{0}\triangleright p\bef\gunderline{\phi\bef\pi_{1}^{\uparrow N}}=\gunderline{p\rightarrow s_{0}\triangleright p\bef\pi_{1}^{\uparrow M}}\bef\phi=\text{brun}\,(s_{0})\bef\phi\quad.
\end{align*}


\subsection{Transformer for the continuation monad. Proofs}

The continuation monad transformer\textsf{'}s type constructor \lstinline!ContT[R, M[_], *]!
is defined by
\[
T_{\text{Cont}}^{M,A}\triangleq(A\rightarrow M^{R})\rightarrow M^{R}\quad.
\]
Unlike most other monad transformers, $T_{\text{Cont}}$ is not covariant
in the foreign monad $M$: the type $T_{\text{Cont}}^{M,A}$ contains
$M$ both in covariant and contravariant positions. (In the language
of categories, $T_{\text{Cont}}$ is not a functor in the category
of monads.) As a result, we cannot define the foreign runner or the
base lift functions. This limits the usability of the continuation
monad transformer. 

Another limitation comes from the fact that the \lstinline!Cont!
monad does not have a fully parametric runner of type $\forall A.\,\text{Cont}^{R,A}\rightarrow A$.
The derivation techniques developed in this book apply only to fully
parametric code. The runners constructed in Section~\ref{subsec:The-continuation-monad}
are not fully parametric and will terminate only for values of type
$\text{Cont}^{R,A}$ that eventually call their callbacks (of type
$A\rightarrow R$). Accordingly, the transformer \lstinline!ContT!
does not have fully parametric base runners, and we will not verify
their laws. Nevertheless, we will prove that the remaining laws of
\lstinline!ContT! hold.

\paragraph{Monad laws}

The transformed monad $T_{\text{Cont}}^{M}$ differs from the continuation
monad \lstinline!Cont! only in the type of the result ($R$), replacing
$\left(A\rightarrow R\right)\rightarrow R$ by $(A\rightarrow M^{R})\rightarrow M^{R}$.
The monad\textsf{'}s methods work the same way for all result types, so $T_{\text{Cont}}^{M}$
is a monad for all monads $M$. (This would remain true even if the
type constructor $M$ were not a functor!)

\paragraph{Identity laws}

If we set $M=\text{Id}$, the type of $T_{\text{Cont}}^{M,A}$ is
equivalent to the base monad, $\left(A\rightarrow R\right)\rightarrow R$.

\paragraph{Lifting laws}

The foreign lift function (\lstinline!flift!) is defined by
\[
\text{flift}:M^{A}\rightarrow(A\rightarrow M^{R})\rightarrow M^{R}\quad,\quad\quad\text{flift}\triangleq\text{flatMap}_{M}=m^{:M^{A}}\rightarrow f^{:A\rightarrow M^{R}}\rightarrow m\triangleright\text{flm}_{M}(f)\quad.
\]
To verify that \lstinline!flift! is a monad morphism, we use the
flipped Kleisli formulation for $T_{\text{Cont}}$. In that formulation,
Kleisli functions of type $A\rightarrow T_{\text{Cont}}^{M,B}=A\rightarrow(B\rightarrow M^{R})\rightarrow M^{R}$
are flipped into the type signature $(B\rightarrow M^{R})\rightarrow A\rightarrow M^{R}$.
For the \lstinline!Cont! monad, the flipped Kleisli composition is
equal to the ordinary \emph{backward} function composition (see Statement~\ref{subsec:Statement-continuation-monad-is-lawful}):
\begin{equation}
f^{:(B\rightarrow M^{R})\rightarrow A\rightarrow M^{R}}\,\tilde{\diamond}_{_{T}}\,g^{:(C\rightarrow M^{R})\rightarrow B\rightarrow M^{R}}=(g\bef f)^{:(C\rightarrow M^{R})\rightarrow A\rightarrow M^{R}}\quad.\label{eq:continuation-transformer-derivation1}
\end{equation}
Let us also compute the result of flipping a lifted $M$-Kleisli function:
\begin{equation}
\text{flip}\,(f^{:A\rightarrow M^{B}}\bef\text{flift})=p^{:B\rightarrow M^{R}}\rightarrow a^{:A}\rightarrow f(a)\triangleright\text{flm}_{M}(p)=p\rightarrow f\bef\text{flm}_{M}(p)=p\rightarrow f\diamond_{_{M}}p\quad.\label{eq:continuation-transformer-flip-derivation2}
\end{equation}

The identity law of \lstinline!flift! is now easy to verify. The
flipped \lstinline!pure! method for $T_{\text{Cont}}$ is 
\[
\tilde{\text{pu}}_{T}:(A\rightarrow M^{R})\rightarrow A\rightarrow M^{R}\quad,\quad\quad\tilde{\text{pu}}_{T}=\text{id}^{A\rightarrow M^{R}}\quad.
\]
To show that the law holds, we write:
\begin{align*}
{\color{greenunder}\text{expect to equal }\tilde{\text{pu}}_{T}:}\quad & \text{flip}\,(\text{pu}_{M}\bef\text{flift})=p\rightarrow\gunderline{\text{pu}_{M}\,\diamond_{_{M}}}p=p\rightarrow p=\text{id}=\tilde{\text{pu}}_{T}\quad.
\end{align*}

The composition law in the ordinary Kleisli formulation is
\[
\big(f^{:A\rightarrow M^{B}}\bef\text{flift}\big)\diamond_{_{T}}\big(g^{:B\rightarrow M^{C}}\bef\text{flift}\big)\overset{?}{=}(f\diamond_{_{M}}g)\bef\text{flift}\quad.
\]
To transform the composition law to the flipped Kleisli formulation,
we write:
\[
\text{flip}\,(f\bef\text{flift})\,\tilde{\diamond}_{_{T}}\,\text{flip}\,(g\bef\text{flift})\overset{?}{=}\text{flip}\,\big((f\diamond_{_{M}}g)\bef\text{flift}\big)\quad.
\]
We complete the proof by using Eqs.~(\ref{eq:uncurry-state-composition-derivation1})\textendash (\ref{eq:state-transformer-derivation2})
and the associativity of $\diamond_{_{M}}$:
\begin{align*}
 & \text{flip}\,(f\bef\text{flift})\,\tilde{\diamond}_{_{T}}\,\text{flip}\,(g\bef\text{flift})=(q\rightarrow g\diamond_{_{M}}q)\bef(p\rightarrow f\diamond_{_{M}}p)=q\rightarrow\gunderline{f\diamond_{_{M}}(g\diamond_{_{M}}q)}\\
 & =q\rightarrow(f\diamond_{_{M}}g)\diamond_{_{M}}q=\text{flip}\,\big((f\diamond_{_{M}}g)\bef\text{flift}\big)\quad.
\end{align*}


\subsection{Transformer for the generalized \texttt{Search} monad. Proofs\label{subsec:Transformer-for-the-generalized-search-monad}}

The generalized\index{monads!generalized Search monad@generalized \texttt{Search} monad}
\lstinline!Search! monad is defined, for a fixed monad $L$ and a
fixed type $Q$, by
\[
\text{Search}^{L,Q,A}\triangleq(A\rightarrow L^{Q})\rightarrow L^{A}\quad.
\]
The ordinary \lstinline!Search! monad is obtained with $L\triangleq\text{Opt}$
and $Q\triangleq\bbnum 1$.

\subsubsection{Statement \label{subsec:Statement-generalized-search-monad}\ref{subsec:Statement-generalized-search-monad}}

The transformer type for the generalized \lstinline!Search! monad
is given by
\[
T_{\text{Search}}^{M,A}\triangleq(A\rightarrow T_{L}^{M,Q})\rightarrow T_{L}^{M,A}\quad,
\]
where $L$ is any fixed monad and $T_{L}$ is the monad $L$\textsf{'}s transformer.
Like the continuation monad, the \lstinline!Search! monad\textsf{'}s transformer
has no base lift, foreign runner, or base runner functions.

\subparagraph{Proof}

We assume that $T_{L}$ already satisfies all the necessary transformer
laws.

\paragraph{Monad laws}

The monad laws hold for $\text{Search}^{L,Q,A}$ due to Statement~\ref{subsec:Statement-monad-construction-3},
where we use the $L$-filterable contrafunctor $A\rightarrow L^{Q}$
as $H^{A}$ (see Statement~\ref{subsec:Statement-examples-of-filterable-contrafunctors}).
Similarly, we find that the monad laws hold for $T_{\text{Search}}^{M,A}$
if we use the $T_{L}^{M}$-filterable contrafunctor $H^{A}\triangleq A\rightarrow T_{L}^{M,Q}$,
where we may assume that $T_{L}^{M}$ is a lawful monad. We will use
this definition of $H^{A}$ in the proof below. For brevity, let us
also write simply $T$ instead of $T_{\text{Search}}^{M}$ (the foreign
monad $M$ will be fixed throughout the derivations). 

The monad methods of $T_{\text{Search}}^{M}\triangleq T$ are defined
according to Statement~\ref{subsec:Statement-monad-construction-3}:
\begin{align*}
 & \text{pu}_{T}\triangleq a^{:A}\rightarrow\big(\_^{:H^{A}}\big)\rightarrow\text{pu}_{T_{L}}(a)\quad,\\
 & f^{:H^{B}\rightarrow A\rightarrow T_{L}^{M,B}}\tilde{\diamond}_{_{T}}g^{:H^{C}\rightarrow A\rightarrow T_{L}^{M,C}}\triangleq h^{:H^{C}}\rightarrow f\big(h\triangleright\text{lift}_{T_{L}^{M},H}(g(h))\big)\diamond_{_{T_{L}}}g(h)\quad,\\
{\color{greenunder}\text{where we defined}:}\quad & \text{lift}_{T_{L}^{M},H}\triangleq f^{:A\rightarrow T_{L}^{M,B}}\rightarrow h^{:B\rightarrow T_{L}^{M,Q}}\rightarrow f\diamond_{_{T_{L}^{M}}}h\quad.
\end{align*}
Derivations are shorter if we use the flipped Kleisli composition
operation $\tilde{\diamond}_{_{T}}$ and the (ordinary) Kleisli composition
$\diamond_{_{T_{L}}}$ of the monad $T_{L}^{M}$.

\paragraph{Identity laws}

We need to establish monad isomorphisms between the monads $R^{A}\triangleq(A\rightarrow L^{Q})\rightarrow L^{A}$
and $S^{A}\triangleq(A\rightarrow T_{L}^{\text{Id},Q})\rightarrow T_{L}^{\text{Id},A}$.
Denote for brevity $N^{A}\triangleq T_{L}^{\text{Id},A}$. Our goal
is to implement monad morphisms $p$ and $q$,
\[
p:\big((A\rightarrow L^{Q})\rightarrow L^{A}\big)\rightarrow(A\rightarrow N^{Q})\rightarrow N^{A}\quad,\quad\quad q:\big((A\rightarrow N^{Q})\rightarrow N^{A}\big)\rightarrow(A\rightarrow L^{Q})\rightarrow L^{A}\quad,
\]
such that $p\bef q=\text{id}$ and $q\bef p=\text{id}$. We may assume
that the identity laws already hold for the transformer $T_{L}$.
These laws imply that there exist two monad morphisms,
\[
r^{A}:L^{A}\rightarrow N^{A}\quad,\quad\quad s^{A}:N^{A}\rightarrow L^{A}\quad,
\]
 satisfying the laws $r\bef s=\text{id}$ and $s\bef r=\text{id}$.
We may use $r$ and $s$ as given functions.

The listed requirements use $L$ and $N$ in the same way. So, the
implementations of $p$ and $q$ will be the same up to exchanging
$r$ with $s$, and it will be sufficient to prove one of the laws
(say, $p\bef q=\text{id}$).

To find the code for $p$, we use typed holes:
\begin{align*}
 & p\triangleq u^{:(A\rightarrow L^{Q})\rightarrow L^{A}}\rightarrow v^{:A\rightarrow N^{Q}}\rightarrow\text{???}^{:N^{A}}=u\rightarrow v\rightarrow(\text{???}^{:A\rightarrow L^{Q}})\triangleright u\triangleright r^{A}\\
 & =u\rightarrow v\rightarrow(\text{???}^{:A\rightarrow N^{Q}}\bef s^{Q})\triangleright u\triangleright r=u\rightarrow v\rightarrow(v\bef s)\triangleright u\bef r\quad.
\end{align*}
The code for $q$ is found by exchanging $r$ and $s$ in the code
of $p$:
\[
q\triangleq t^{:(A\rightarrow N^{Q})\rightarrow N^{A}}\rightarrow w^{:A\rightarrow L^{Q}}\rightarrow(w\bef r)\triangleright t\bef s\quad.
\]

To verify that $p\bef q=\text{id}$, we use the assumption $r\bef s=\text{id}$:
\begin{align*}
 & p\bef q=\big(u\rightarrow\gunderline{v\rightarrow(v\bef s)\triangleright u\bef r}\big)\bef\big(\gunderline t\rightarrow w\rightarrow(w\bef r)\triangleright\gunderline t\bef s\big)\\
{\color{greenunder}\text{compute composition}:}\quad & =u\rightarrow w\rightarrow\gunderline{(w\bef r)\triangleright\big(v}\rightarrow(v\bef s)\triangleright u\bef r\big)\bef s\\
{\color{greenunder}\text{apply function}:}\quad & =u\rightarrow w\rightarrow(w\bef\gunderline{r\bef s})\triangleright u\bef\gunderline{r\bef s}=u\rightarrow(\gunderline{w\rightarrow w\,\triangleright}\,u)=u\rightarrow u=\text{id}\quad.
\end{align*}
A separate proof for $q\bef p=\text{id}$ is not needed.

It remains to prove that $p$ is a monad morphism (the same will then
hold for $q$).

To verify the identity law:
\begin{align*}
{\color{greenunder}\text{expect to equal }a\triangleright\text{pu}_{S}:}\quad & a\triangleright\text{pu}_{R}\bef p=\big((\_^{:A\rightarrow L^{Q}})\rightarrow a\triangleright\text{pu}_{L}\big)\triangleright p=\gunderline v\rightarrow a\triangleright\gunderline{\text{pu}_{L}\bef r}\\
{\color{greenunder}v\text{ is not used}:}\quad & =\_\rightarrow a\triangleright\text{pu}_{N}=a\triangleright\text{pu}_{S}\quad.
\end{align*}

To verify the composition law, we use the flipped Kleisli\index{flipped@\textsf{``}flipped Kleisli\textsf{''} technique}
formulation. The flipped Kleisli composition for the monad $R$ is
defined by
\[
f^{:(B\rightarrow L^{Q})\rightarrow A\rightarrow L^{B}}\tilde{\diamond}_{_{T}}g^{:(C\rightarrow L^{Q})\rightarrow B\rightarrow L^{C}}\triangleq h^{:H^{C}}\rightarrow f\big(h\triangleright\text{lift}_{L,H}(g(h))\big)\diamond_{_{L}}g(h)\quad,
\]
and similarly for the monad $S$ (except for using $N$ instead of
$L$ and a corresponding change in the definition of $H$). The next
step is to modify $p$ into a more convenient function, $\tilde{p}$,
that directly transforms flipped Kleisli functions in the monad $R$
into those in $S$:
\begin{align*}
 & \tilde{p}:\big((B\rightarrow L^{Q})\rightarrow A\rightarrow L^{B}\big)\rightarrow(B\rightarrow N^{Q})\rightarrow A\rightarrow N^{B}\quad,\\
 & \tilde{p}\triangleq k^{:(B\rightarrow L^{Q})\rightarrow A\rightarrow L^{B}}\rightarrow h^{:B\rightarrow N^{Q}}\rightarrow k(h\bef s)\bef r\quad.
\end{align*}
We may now rewrite the composition law using $\tilde{p}$:
\[
\tilde{p}\big(f^{:(B\rightarrow L^{Q})\rightarrow A\rightarrow L^{B}}\tilde{\diamond}_{_{R}}g^{:(C\rightarrow L^{Q})\rightarrow B\rightarrow L^{C}}\big)\overset{?}{=}\tilde{p}(f)\tilde{\diamond}_{_{S}}\tilde{p}(g)\quad.
\]
Rewrite the left-hand side:
\begin{align*}
 & \tilde{p}\big(f\tilde{\diamond}_{_{R}}g\big)=\gunderline{\tilde{p}}\big(h\rightarrow f\big(h\triangleright\text{lift}_{L,H}(g(h))\big)\diamond_{_{L}}g(h)\big)\\
{\color{greenunder}\text{definition of }\tilde{p}:}\quad & =h\rightarrow\big(f\big((h\bef s)\triangleright\text{lift}_{L,H}(g(h\bef s))\big)\gunderline{\diamond_{_{L}}}g(h\bef s)\big)\,\gunderline{\bef\,r}\\
{\color{greenunder}\text{composition law of }r:}\quad & =h\rightarrow\big(f\big((h\bef s)\triangleright\text{lift}_{L,H}(g(h\bef s))\big)\bef r\big)\diamond_{_{N}}\big(g(h\bef s)\bef r\big)\quad.
\end{align*}
Rewrite the right-hand side:
\begin{align*}
 & \tilde{p}(f)\tilde{\diamond}_{_{S}}\tilde{p}(g)=\big(h\rightarrow f(h\bef s)\bef r\big)\tilde{\diamond}_{_{S}}\big(h\rightarrow g(h\bef s)\bef r\big)\\
 & =h\rightarrow\big(h\rightarrow f(h\bef s)\bef r\big)(h\triangleright\text{lift}_{N,H}(\big(h\rightarrow g(h\bef s)\bef r\big)(h)))\diamond_{_{N}}\big(h\rightarrow g(h\bef s)\bef r\big)(h)\\
 & =h\rightarrow\big(f((h\triangleright\text{lift}_{N,H}(g(h\bef s)\bef r))\bef s)\bef r\big)\diamond_{_{N}}\big(g(h\bef s)\bef r\big)\quad.
\end{align*}
The remaining difference between the two sides is
\begin{equation}
(h\bef s)\triangleright\text{lift}_{L,H}(g(h\bef s))\overset{?}{=}\big(h\triangleright\text{lift}_{N,H}(g(h\bef s)\bef r)\big)\bef s\quad.\label{eq:identity-law-search-monad-transformer-derivation1}
\end{equation}
To proceed, we need to use the code of the lifting functions $\text{lift}_{L,H}$
and $\text{lift}_{N,H}$:
\begin{align*}
 & \text{lift}_{L,H}:(A\rightarrow L^{B})\rightarrow(B\rightarrow L^{Q})\rightarrow A\rightarrow L^{Q}\quad,\quad\quad g^{:B\rightarrow L^{Q}}\triangleright\text{lift}_{L,H}(f^{:A\rightarrow L^{B}})=f\diamond_{_{L}}g\quad,\\
 & \text{lift}_{N,H}:(A\rightarrow N^{B})\rightarrow(B\rightarrow N^{Q})\rightarrow A\rightarrow N^{Q}\quad,\quad\quad g^{:B\rightarrow N^{Q}}\triangleright\text{lift}_{N,H}(f^{:A\rightarrow N^{B}})=f\diamond_{_{N}}g\quad.
\end{align*}
Substituting the code of those functions into both sides of Eq.~(\ref{eq:identity-law-search-monad-transformer-derivation1}),
we get:
\begin{align*}
{\color{greenunder}\text{left-hand side}:}\quad & (h\bef s)\triangleright\text{lift}_{L,H}(g(h\bef s))=g(h\bef s)\diamond_{_{L}}(h\bef s)\\
 & \overset{?}{=}\big(h\triangleright\text{lift}_{N,H}(g(h\bef s)\bef r)\big)\bef s=\big((g(h\bef s)\bef r)\,\gunderline{\diamond_{_{N}}}h\big)\gunderline{\bef s}\\
{\color{greenunder}\text{composition law of }s:}\quad & =\quad\big(g(h\bef s)\bef\gunderline{r\bef s}\big)\diamond_{_{L}}(h\bef s)=g(h\bef s)\diamond_{_{L}}(h\bef s)\quad.
\end{align*}
Both sides are now equal.

\paragraph{Lifting laws}

The \lstinline!flift! function of the \lstinline!Search! monad transformer
is defined by
\[
\text{flift}:\quad M^{A}\rightarrow(A\rightarrow T_{L}^{M,Q})\rightarrow T_{L}^{M,A}\quad,\quad\quad\text{flift}\triangleq m^{:M^{A}}\rightarrow\big(\_^{:H^{A}}\big)\rightarrow m\triangleright\text{flift}_{L}\quad,
\]
where $\text{flift}_{L}:M^{A}\rightarrow T_{L}^{M,A}$ is the transformer
$T_{L}$\textsf{'}s foreign lift function.

To show that \lstinline!flift! is a monad morphism, begin with the
identity law:
\begin{align*}
{\color{greenunder}\text{expect to equal }a\triangleright\text{pu}_{T}:}\quad & a^{:A}\triangleright\text{pu}_{M}\bef\text{flift}=\big(\_^{:A\rightarrow T_{L}^{M,Q}}\big)\rightarrow a\triangleright\gunderline{\text{pu}_{M}\bef\text{flift}_{L}}\\
{\color{greenunder}\text{identity law of }\text{flift}_{L}:}\quad & =\big(\_^{:A\rightarrow T_{L}^{M,Q}}\big)\rightarrow a\triangleright\text{pu}_{T_{L}}\\
{\color{greenunder}\text{definition of }\text{pu}_{T}:}\quad & =a\triangleright\text{pu}_{T}\quad.
\end{align*}
To verify the composition law, we note that \lstinline!flift! always
produces functions that ignore their argument of type $H^{A}$. For
such values, the Kleisli composition $\tilde{\diamond}_{_{T}}$ may
be simplified: If we know that the functions $f^{:H^{B}\rightarrow A\rightarrow T_{L}^{M,B}}$
and $g^{:H^{C}\rightarrow A\rightarrow T_{L}^{M,C}}$ ignore their
first arguments, we may write
\[
f\,\tilde{\diamond}_{_{T}}g=k^{:H^{C}}\rightarrow f(...)\diamond_{_{T_{L}}}g(...)=(\_^{:H^{C}})\rightarrow f(...)\diamond_{_{T_{L}}}g(...)\quad.
\]
So, the Kleisli composition also always produces functions that ignore
their first arguments. We can then simplify the formulas, since $\diamond_{_{T}}$
reduces to the Kleisli composition $\diamond_{_{T_{L}}}$ of the monad
$T_{L}^{M}$. To make use of this simplification, we need to flip
the arguments of Kleisli functions. First, we find, for any function
$p^{:A\rightarrow M^{B}}$,
\[
\text{flip}\,(p^{:A\rightarrow M^{B}}\bef\text{flift})=(\_^{:H^{B}})\rightarrow\gunderline{a^{:A}\rightarrow a\,\triangleright}\,p\triangleright\text{flift}_{L}=(\_^{:H^{B}})\rightarrow p\bef\text{flift}_{L}\quad.
\]
Now we can show that \lstinline!flift!\textsf{'}s composition law holds:
\begin{align*}
{\color{greenunder}\text{expect }(p\diamond_{_{M}}q)\bef\text{flift}:}\quad & \big(p^{:A\rightarrow M^{B}}\bef\text{flift}\big)\diamond_{_{T}}\big(q^{:B\rightarrow M^{C}}\bef\text{flift}\big)=\text{flip}\,\big(\gunderline{\text{flip}\,(p\bef\text{flift})}\tilde{\diamond}_{_{T}}\gunderline{\text{flip}\,(q\bef\text{flift})}\big)\\
 & =\text{flip}\,\big((\_\rightarrow p\bef\text{flift}_{L})\,\tilde{\diamond}_{_{T}}(\_\rightarrow q\bef\text{flift}_{L})\big)=\text{flip}\,\big(\_\rightarrow\gunderline{(p\bef\text{flift}_{L})\diamond_{_{T_{L}}}(q\bef\text{flift}_{L})}\big)\\
{\color{greenunder}\text{flift}_{L}\text{\textsf{'}s composition law}:}\quad & =\text{flip}\,\big(\gunderline{\_\rightarrow(p\diamond_{_{M}}q)\bef\text{flift}_{L}}\big)=\gunderline{\text{flip}\,\big(\text{flip}}\,((p\diamond_{_{M}}q)\bef\text{flift})\big)\\
{\color{greenunder}\text{use }\text{flip}\bef\text{flip}=\text{id}:}\quad & =(p\diamond_{_{M}}q)\bef\text{flift}\quad.
\end{align*}


\subsection{The codensity monad and its transformer. Proofs\label{subsec:The-codensity-monad}}

For any type constructor $F$, the \index{monads!codensity monad|textit}\textbf{codensity
monad}\footnote{See, e.g., the talk \texttt{\href{https://begriffs.com/posts/2016-02-04-difference-lists-and-codennsity.html}{https://begriffs.com/posts/2016-02-04-difference-lists-and-codennsity.html}}
for applications of the codensity monad in functional programming
and for more references.} \textbf{on} $F$ is defined by 
\[
\text{Cod}^{F,A}\triangleq\forall R.\,(A\rightarrow F^{R})\rightarrow F^{R}\quad.
\]
Before considering its transformer, we will establish some properties
of this monad.

Note the similarity of $\text{Cod}^{F,A}$ with the continuation monad
$\text{Cont}^{F^{R},A}=(A\rightarrow F^{R})\rightarrow F^{R}$ whose
\textsf{``}return type\textsf{''} is $F^{R}$. The difference is that $\text{Cod}^{F,A}$
imposes a universal quantifier ($\forall R$) on the type parameter
$R$:
\[
\text{Cod}^{F,A}=\forall R.\,\text{Cont}^{F^{R},A}\quad.
\]
 Many of the properties of the continuation monad continue to hold
after adding $\forall R$. In general, adding a type quantifier preserves
monad laws:

\subsubsection{Statement \label{subsec:Statement-monad-with-quantifier}\ref{subsec:Statement-monad-with-quantifier} }

Assume a monad $K^{R,\bullet}$ with an extra type parameter $R$;
so, $K^{R,A}$ is a lawful monad (with respect to the type parameter
$A$ and with a fixed $R$). Then \textbf{(a)} $L^{A}\triangleq\forall R.\,K^{R,A}$
is also a lawful monad, and \textbf{(b)} for any fixed $R$, there
is a monad morphism $L^{\bullet}\leadsto K^{R,\bullet}$.

\subparagraph{Proof}

\textbf{(a)} We need to define the monad $L$\textsf{'}s methods and verify
the laws. The idea is to add the quantifier ($\forall R$) to monad
$K$\textsf{'}s methods. (For brevity, we will sometimes write $K$ to mean
$K^{R,\bullet}$.) Begin with the method \lstinline!pure!:
\[
\text{pu}_{L}\triangleq\forall R.\,\text{pu}_{K^{R,\bullet}}=\forall R.\,a^{:A}\rightarrow\text{pu}_{K^{R,\bullet}}(a)=a^{:A}\rightarrow\forall R.\,\text{pu}_{K^{R,\bullet}}(a)\quad.
\]
Here, we may move the quantifier as $\forall R.a^{:A}\rightarrow(...)^{R}=a^{:A}\rightarrow\forall R.\,(...)^{R}$
because the type parameter $A$ does not depend on $R$.

To define the \lstinline!flatMap! method for $L$, we add quantifiers
to the \lstinline!flatMap! method of $K$,
\[
\text{flm}_{K}(f^{:A\rightarrow K^{R,B}})(d^{:K^{R,A}}):K^{R,B}\quad,
\]
and to its two curried arguments ($f$ and $d$). To write the resulting
code, we need to use distinct type parameters $R$, $S$, $T$ for
the arguments $f$, $d$ and for the return value respectively: 
\[
\text{flm}_{L}(f^{:\forall R.\,A\rightarrow K^{R,B}})\triangleq d^{:\forall S.\,K^{S,A}}\rightarrow\forall T.\,\text{flm}_{K}(f^{T})(d^{T})\quad.
\]
The arguments $f$ and $d$ of $\text{flm}_{L}$ have their own type
parameters ($R$ and $S$), and we \emph{assign} those type parameters
to the type $T$ in the expression $\text{flm}_{K}(f^{T})(d^{T})$.

To verify the monad laws for $L$, we use the Kleisli formulation.
To define the Kleisli composition ($\diamond_{_{L}}$) for $L$, we
use two different universally quantified types ($R$, $S$) to avoid
confusion:
\[
f^{:A\rightarrow L^{B}}\diamond_{_{L}}g^{:B\rightarrow L^{C}}=f^{:\forall R.\,A\rightarrow K^{R,B}}\diamond_{_{L}}g^{:\forall S.\,B\rightarrow K^{S,C}}\triangleq\forall T.\,f^{T}\diamond_{_{K}}g^{T}\quad.
\]
As in the definition of \lstinline!flatMap!, we need to assign the
type parameters $R$ and $S$ to $T$. 

To verify the identity laws, we assume that the same laws hold for
the monad $K$:
\begin{align*}
{\color{greenunder}\text{expect to equal }g:}\quad & \text{pu}_{L}\diamond_{_{L}}g=\forall T.\,\text{pu}_{K^{T,\bullet}}\diamond_{_{K}}g^{T}=\forall T.\,g^{T}=g\quad,\\
{\color{greenunder}\text{expect to equal }f:}\quad & f\diamond_{_{L}}\text{pu}_{L}=\forall T.\,f^{T}\diamond_{_{K}}\text{pu}_{K^{T,\bullet}}=\forall T.\,f^{T}=f\quad.
\end{align*}
To verify the associativity law:
\begin{align*}
{\color{greenunder}\text{left-hand side}:}\quad & (f\diamond_{_{L}}g)\diamond_{_{L}}h=\big(\forall T.\,f^{T}\diamond_{_{K}}g^{T}\big)\diamond_{_{L}}h\\
 & \quad=\forall S.\,\big(\forall T.\,f^{T}\diamond_{_{K}}g^{T}\big)^{S}\diamond_{_{K}}h^{S}=\forall S.\,\big(f^{S}\diamond_{_{K}}g^{S}\big)\diamond_{_{K}}h^{S}\quad,\\
{\color{greenunder}\text{right-hand side}:}\quad & f\diamond_{_{L}}(g\diamond_{_{L}}h)=\forall S.\,f^{S}\diamond_{_{K}}(g\diamond_{_{L}}h)^{S}\\
 & \quad=\forall S.\,f^{S}\diamond_{_{K}}\big(\forall T.\,g^{T}\diamond_{_{K}}h^{T}\big)^{S}=\forall S.\,f^{S}\diamond_{_{K}}(g^{S}\diamond_{_{K}}h^{S})\quad.
\end{align*}
The two sides are equal due to the associativity of the Kleisli composition
($\diamond_{_{K}}$) of the monad $K$.

\textbf{(b)} The monad morphism $\phi:L^{A}\rightarrow K^{R,A}$ is
defined by setting the quantified type parameter $T$ in $L^{A}\triangleq\forall T.\,K^{T,A}$
as $T=R$. The action of $\phi$ on a Kleisli function $f^{:\forall T.\,A\rightarrow K^{T,B}}$
can be written as $f\bef\phi=f^{R}$. To verify that $\phi$ is monad
morphism, begin with the identity law:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{pu}_{K}:}\quad & \text{pu}_{L}\bef\phi=(\forall T.\,\text{pu}_{K^{T,\bullet}})\bef\phi=(\forall T.\,\text{pu}_{K^{T,\bullet}})^{R}=\text{pu}_{K^{R,\bullet}}=\text{pu}_{K}\quad.
\end{align*}
To verify the composition law, we show that its two sides are equal:
\begin{align*}
{\color{greenunder}\text{left-hand side}:}\quad & \big(f^{:\forall R.\,A\rightarrow K^{R,B}}\diamond_{_{L}}g^{:\forall S.\,B\rightarrow K^{S,C}}\big)\bef\phi=(\forall T.\,f^{T}\diamond_{_{K}}g^{T})^{R}=f^{R}\diamond_{_{K}}g^{R}\quad,\\
{\color{greenunder}\text{right-hand side}:}\quad & (f\bef\phi)\diamond_{_{K}}(g\bef\phi)=f^{R}\diamond_{_{K}}g^{R}\quad.
\end{align*}


\subsubsection{Statement \label{subsec:Statement-codensity-monad-lawful}\ref{subsec:Statement-codensity-monad-lawful}}

$\text{Cod}^{F,\bullet}$ is a monad for any type constructor $F$
(not necessarily a functor).

\subparagraph{Proof}

By Statement~\ref{subsec:Statement-monad-with-quantifier}, adding
a quantifier ($\forall R$) to the continuation monad $\text{Cont}^{R,A}$
gives again a lawful monad. $\square$

The next statement shows that $\text{Cod}^{F,\bullet}$ includes the
effects of $F$ when $F$ is itself a monad.

\subsubsection{Statement \label{subsec:Statement-codensity-monad-inC-outC}\ref{subsec:Statement-codensity-monad-inC-outC}}

\textbf{(a)} If $F$ is a monad then there exist functions $\text{inC}:F^{\bullet}\leadsto\text{Cod}^{F,\bullet}$
and $\text{outC}:\text{Cod}^{F,\bullet}\leadsto F^{\bullet}$, such
that $\text{inC}\,\bef\text{outC}=\text{id}$ (so, \lstinline!inC!
is an injection and \lstinline!outC! a surjection). 

\textbf{(b)} The function \lstinline!inC! is a monad morphism $F^{\bullet}\leadsto\text{Cod}^{F,\bullet}$
(while \lstinline!outC! is not a monad morphism).

\textbf{(c)} The functions \lstinline!inC! and \lstinline!outC!
are \emph{not} isomorphisms between the types $F^{A}$ and $\text{Cod}^{F,A}$.

\subparagraph{Proof}

\textbf{(a)} Begin by implementing the functions \lstinline!inC!
and \lstinline!outC!:
\begin{align*}
 & \text{inC}:F^{A}\rightarrow\forall R.\,(A\rightarrow F^{R})\rightarrow F^{R}\quad,\quad\quad\text{inC}^{R,A}\triangleq f^{:F^{A}}\rightarrow k^{:A\rightarrow F^{R}}\rightarrow f\triangleright\text{flm}_{F}(k)\quad,\\
 & \text{outC}:\big(\forall R.\,(A\rightarrow F^{R})\rightarrow F^{R}\big)\rightarrow F^{A}\quad,\quad\quad\text{outC}^{A}\triangleq d^{:\forall R.\,(A\rightarrow F^{R})\rightarrow F^{R}}\rightarrow d^{A}(\text{pu}_{F}^{:A\rightarrow F^{A}})\quad.
\end{align*}
Note that \lstinline!inC! is the same as $F$\textsf{'}s \lstinline!flatMap!,
or $\text{flm}_{F}$ with flipped arguments.

To verify the non-degeneracy law, compute:
\begin{align*}
{\color{greenunder}\text{expect to equal }f:}\quad & f^{:F^{A}}\triangleright\text{inC}\bef\text{outC}=(k\rightarrow f\triangleright\text{flm}_{F}(k))\triangleright\text{outC}\\
 & =(k\rightarrow f\triangleright\text{flm}_{F}(k))(\text{pu}_{F})=f\triangleright\gunderline{\text{flm}_{F}(\text{pu}_{F})}\\
{\color{greenunder}\text{right identity law of }F:}\quad & =f\triangleright\text{id}=f\quad.
\end{align*}

\textbf{(b)} To show that \lstinline!inC! is a monad morphism, we
use the Kleisli composition:
\[
f^{:\forall R.\,A\rightarrow(B\rightarrow F^{R})\rightarrow F^{R}}\diamond_{_{\text{Cod}}}g^{:\forall S.\,B\rightarrow(C\rightarrow F^{S})\rightarrow F^{S}}\triangleq\forall T.\,a^{:A}\rightarrow k^{:C\rightarrow F^{T}}\rightarrow f^{T}(a)\big(b^{:B}\rightarrow g^{T}(b)(k)\big)\quad.
\]
To verify the identity law of \lstinline!inC!:
\begin{align*}
{\color{greenunder}\text{expect to equal }a\triangleright\text{pu}_{\text{Cod}}:}\quad & a^{:A}\triangleright\text{pu}_{F}\bef\text{inC}=\forall R.\,g^{:A\rightarrow F^{R}}\rightarrow a\triangleright\gunderline{\text{pu}_{F}\triangleright\text{flm}_{F}}(g)\\
{\color{greenunder}\text{left identity law of }F:}\quad & =\forall R.\,g^{:A\rightarrow F^{R}}\rightarrow a\triangleright g=\text{pu}_{\text{Cod}}(a)\quad.
\end{align*}
The composition law of \lstinline!inC! is written as
\[
(f^{:A\rightarrow F^{B}}\diamond_{_{F}}g^{:B\rightarrow F^{C}})\bef\text{inC}\overset{?}{=}(f\bef\text{inC})\diamond_{_{\text{Cod}}}(g\bef\text{inC})\quad.
\]
Apply both sides to an arbitrary value $a^{:A}$ and simplify the
results:
\begin{align*}
{\color{greenunder}\text{left-hand side}:}\quad & a^{:A}\triangleright(f\diamond_{_{F}}g)\bef\text{inC}=k\rightarrow a\triangleright(f\diamond_{_{F}}g)\bef\text{flm}_{F}(k)\\
{\color{greenunder}\text{definition of }\diamond_{_{F}}:}\quad & \quad=k\rightarrow a\triangleright f\bef\text{flm}_{F}(g)\bef\text{flm}_{F}(k)\quad,\\
{\color{greenunder}\text{right-hand side}:}\quad & a^{:A}\triangleright\big((f\bef\text{inC})\diamond_{_{\text{Cod}}}(g\bef\text{inC})\big)=k\rightarrow(f\bef\text{inC})^{T}(a)\big(b\rightarrow(g\bef\text{inC})^{T}(b)(k)\big)\quad.
\end{align*}
For clarity, let us simplify the expression $(f\bef\text{inC})^{T}(a)(x)$
separately:
\[
(f\bef\text{inC})^{T}(a)(x)=x\triangleright\big(a\triangleright f\triangleright\text{inC}\big)^{T}=x\triangleright\big(k\rightarrow a\triangleright f\triangleright\text{flm}_{F}(k)\big)=a\triangleright f\triangleright\text{flm}_{F}(x)\quad.
\]
The same simplification applies to the expression $(g\bef\text{inC})^{T}(b)(k)$.
So, the right-hand side becomes:
\begin{align*}
{\color{greenunder}\text{right-hand side}:}\quad & k\rightarrow(f\bef\text{inC})^{T}(a)\big(\gunderline{b\rightarrow b\,\triangleright\,}g\bef\text{flm}_{F}(k)\big)=k\rightarrow\gunderline{(f\bef\text{inC})(a)}(g\bef\text{flm}_{F}(k))\\
 & =k\rightarrow a\triangleright f\triangleright\gunderline{\text{flm}_{F}(g\bef\text{flm}_{F}(k))}=k\rightarrow a\triangleright f\triangleright\text{flm}_{F}(g)\bef\text{flm}_{F}(k)\quad.
\end{align*}
The two sides of the law are now equal.

As for the function \lstinline!outC!, it does satisfy the identity
law of monad morphisms:
\begin{align*}
{\color{greenunder}\text{expect to equal }a\triangleright\text{pu}_{F}:}\quad & a^{:A}\triangleright\text{pu}_{\text{Cod}}\bef\text{outC}=\big(\forall R.\,g^{:A\rightarrow F^{R}}\rightarrow a\triangleright g\big)\triangleright\text{outC}\\
{\color{greenunder}\text{definition of }\text{outC}:}\quad & =\big(\forall R.\,g^{:A\rightarrow F^{R}}\rightarrow a\triangleright g\big)^{A}(\text{pu}_{F})=a\triangleright\text{pu}_{F}\quad.
\end{align*}
But the composition law does not hold in general:
\[
\big(f^{:\forall R.\,A\rightarrow(B\rightarrow F^{R})\rightarrow F^{R}}\diamond_{_{\text{Cod}}}g^{:\forall S.\,B\rightarrow(C\rightarrow F^{S})\rightarrow F^{S}}\big)\bef\text{outC}\overset{?}{=}(f\bef\text{outC})\diamond_{_{F}}(g\bef\text{outC})\quad.
\]
Apply both sides to an arbitrary value $a^{:A}$ and simplify the
results:
\begin{align*}
{\color{greenunder}\text{left-hand side}:}\quad & a\triangleright(f\diamond_{_{\text{Cod}}}g)\bef\text{outC}=\big(\forall T.\,k\rightarrow f^{T}(a)\big(b\rightarrow g^{T}(b)(k)\big)\big)\bef(d\rightarrow d(\text{pu}_{F}))\\
 & \quad=\big(\forall T.\,k\rightarrow f^{T}(a)\big(b\rightarrow g^{T}(b)(k)\big)\big)(\text{pu}_{F})=f(a)(b\rightarrow g(b)(\text{pu}_{F}))\quad.\\
{\color{greenunder}\text{right-hand side}:}\quad & a\triangleright\big((f\bef\text{outC})\diamond_{_{F}}(g\bef\text{outC})\big)=a\triangleright(f\bef\text{outC})\bef\text{flm}_{F}(g\bef\text{outC})\\
 & \quad=a\triangleright f\triangleright\text{outC}\triangleright\text{flm}_{F}(g\bef\text{outC})=f(a)(\text{pu}_{F})\triangleright\text{flm}_{F}\big(b\rightarrow g(b)(\text{pu}_{F})\big)\quad.
\end{align*}
We find two different expressions that cannot be transformed into
each other:
\[
f(a)(b\rightarrow g(b)(\text{pu}_{F}))\neq f(a)(\text{pu}_{F})\triangleright\text{flm}_{F}\big(b\rightarrow g(b)(\text{pu}_{F})\big)\quad.
\]
There are no laws that would allow us to replace $\text{pu}_{F}$
in the \emph{argument} of $f$ because $f$ is an arbitrary function.
In part (c) of this proof, we will see an example that violates the
composition law of \lstinline!outC!.

\textbf{(c)} The functions \lstinline!inC! and \lstinline!outC!
are not isomorphisms because $\text{outC}\bef\text{inC}\not=\text{id}$.
To show this, choose $F^{A}\triangleq R\rightarrow A$ (the \lstinline!Reader!
monad) and simplify the type $\text{Cod}^{F,A}$ using the Yoneda
identity:
\[
\text{Cod}^{F,A}=\forall B.\,(\gunderline{A\rightarrow R}\rightarrow B)\rightarrow\gunderline{R\rightarrow}\,B=R\rightarrow\gunderline{\forall B.\,(A\times R\rightarrow B)\rightarrow B}=R\rightarrow A\times R\quad.
\]
The resulting type constructor is the \lstinline!State! monad ($\text{State}^{R,A}$),
which includes the effect of \lstinline!Reader! and additionally
the effect of changing a value of type $R$ and passing it to the
next computation (which \lstinline!Reader! cannot do). 

For this choice of $F$, the functions \lstinline!inC! and \lstinline!outC!
are defined as
\begin{align*}
 & \text{inC}:\left(R\rightarrow A\right)\rightarrow R\rightarrow A\times R\quad,\quad\quad\text{inC}\triangleq g^{:R\rightarrow A}\rightarrow r^{:R}\rightarrow g(r)\times r\quad,\\
 & \text{outC}:\left(R\rightarrow A\times R\right)\rightarrow R\rightarrow A\quad,\quad\quad\text{outC}\triangleq s^{:R\rightarrow A\times R}\rightarrow r^{:R}\rightarrow s(r)\triangleright\pi_{1}\quad.
\end{align*}
(These type signatures admit no other fully parametric implementations.)
The function \lstinline!outC! is a flipped version of the \lstinline!State!
monad\textsf{'}s runner. That runner returns the result value of type $A$
but discards the possibly changed state (of type $R$). The failure
of the composition law for the \lstinline!State! monad\textsf{'}s runner has
been already noted in the proof of Statement~\ref{subsec:Statement-state-monad-transformer}.

To obtain a specific example showing that $\text{outC}\bef\text{inC}\neq\text{id}$,
consider $R\triangleq\bbnum 1+P$ with some fixed type $P$ and define
a monadic value $s:\text{State}^{R,R}$ by 
\[
s:\bbnum 1+P\rightarrow\left(\bbnum 1+P\right)\times\left(\bbnum 1+P\right)\quad,\quad\quad s\triangleq r^{:\bbnum 1+P}\rightarrow r\times\left(\bbnum 1+\bbnum 0\right)\quad.
\]
Let us now compute $s\triangleright\text{outC}\bef\text{inC}$ and
check that the result is not equal to $s$:
\begin{align*}
 & s\triangleright\text{outC}=r^{:\bbnum 1+P}\rightarrow s(r)\triangleright\pi_{1}=r\rightarrow r=\text{id}\quad,\\
 & s\triangleright\text{outC}\triangleright\text{inC}=\text{id}\triangleright\text{inC}=r\rightarrow r\times r\neq s=r\rightarrow r\times\left(\bbnum 1+\bbnum 0\right)\quad.
\end{align*}
This proves directly that $\text{outC}\bef\text{inC}\neq\text{id}$
for certain monads $F$. $\square$

This proof shows that $\text{Cod}^{F,\bullet}$ may support some additional
effects not described by the monad $F$. So, $\text{Cod}^{F,\bullet}$
and $F$ cannot be equivalent in general. An example when the equivalence
$\text{Cod}^{F,A}\cong F^{A}$ nevertheless holds is found by setting
$F=\text{Id}$:
\[
\text{Cod}^{\text{Id},\bullet}=\forall R.\,(A\rightarrow R)\rightarrow R\cong A=\text{Id}^{A}\quad.
\]


\subsubsection{Statement \label{subsec:Statement-codensity-monad-transformer}\ref{subsec:Statement-codensity-monad-transformer}}

A monad transformer for $\text{Cod}^{F,\bullet}$ can be defined by
\[
T_{\text{Cod}}^{M,A}\triangleq\forall R.\,(A\rightarrow M^{F^{R}})\rightarrow M^{F^{R}}\quad.
\]
This assumes a lawful foreign monad $M$, while $F$ may be any type
constructor. The transformer $T_{\text{Cod}}$ does not have the base
lift, foreign runner, or base runner methods.

\subparagraph{Proof }

Similarly to the continuation monad\textsf{'}s transformer, we only prove three
groups of laws.

\paragraph{The monad laws}

holds for $T_{\text{Cod}}^{M,A}$ due to Statement~\ref{subsec:Statement-codensity-monad-lawful},
where we need to replace the type constructor $F$ by the composition
$M^{F^{\bullet}}$.

\paragraph{The identity laws}

When $M=\text{Id}$, the type $T_{\text{Cod}}^{\text{Id},A}$ is the
same as $\text{Cod}^{F,A}$, so the isomorphism is given by identity
functions. Laws always hold for identity functions.

\paragraph{The lifting laws}

require implementing a monad morphism \lstinline!flift! with type
$M^{A}\rightarrow T_{\text{Cod}}^{M,A}$:
\[
\text{flift}:M^{A}\rightarrow\forall R.\,(A\rightarrow M^{F^{R}})\rightarrow M^{F^{R}}\quad,\quad\quad\text{flift}\triangleq\forall R.\,m^{:M^{A}}\rightarrow k^{:A\rightarrow M^{F^{R}}}\rightarrow m\triangleright\text{flm}_{M}(k)\quad.
\]
We note that the code of \lstinline!flift! is the same as the code
of the function \lstinline!inC! from Statement~\ref{subsec:Statement-codensity-monad-inC-outC}:
\[
\text{inC}:M^{A}\rightarrow\forall S.\,(A\rightarrow M^{S})\rightarrow M^{S}\quad,\quad\quad\text{inC}\triangleq\forall S.\,m^{:M^{A}}\rightarrow k^{:A\rightarrow M^{S}}\rightarrow m\triangleright\text{flm}_{M}(k)\quad,
\]
where we renamed $F$ to $M$ and $R$ to $S$ to make the comparison
easier. The difference between \lstinline!flift! and \lstinline!inC!
is only in the universally quantified types. We obtain \lstinline!flift!
from \lstinline!inC! by restricting the type $S$ to types of the
form $F^{R}$ (where $R$ is arbitrary). By Statement~\ref{subsec:Statement-codensity-monad-inC-outC},
the monad morphism laws hold for \lstinline!inC!, where the type
$S$ is unrestricted. So, the same laws will hold for \lstinline!flift!
where $S$ is limited to a subset of possible types. We do not need
to repeat the proofs of those laws.

\subsection{Examples of monads with two different transformers\label{subsec:Examples-of-monads-with-two-different-transformers}}

As a rule, a monad has only one monad transformer. This section shows
two exceptions to that rule: monads with two inequivalent transformers.
As we will see, in both cases one transformer is complete (has all
required methods) but the other is incomplete.

The first example is the selector monad\index{monads!Sel (selector) monad@\texttt{Sel} (selector) monad},
$\text{Sel}^{Q,A}=(A\rightarrow Q)\rightarrow A$. That monad, described
in Section~\ref{subsec:Rigid-monad-construction-1-choice}, has a
composed-outside transformer $T_{1}^{M,A}\triangleq(M^{A}\rightarrow Q)\rightarrow M^{A}$. 

At the same time, $\text{Sel}^{Q,A}$ is equivalent to the generalized
\lstinline!Search! monad (Section~\ref{subsec:Transformer-for-the-generalized-search-monad})
with $L$ chosen to be the identity monad:
\[
\text{Sel}^{Q,A}\cong\text{Search}^{\text{Id},Q,A}\quad.
\]
So, the selector monad $\text{Sel}^{Q,A}$ has another transformer
with the type $T_{2}^{M,A}\triangleq(A\rightarrow M^{Q})\rightarrow M^{A}$. 

The transformers $T_{1}$ and $T_{2}$ cannot be equivalent because
the transformer $T_{1}$ is covariant in the type parameter $M$ while
$T_{2}$ is not. Since the transformer $T_{2}$ is incomplete (it
lacks runners and a base lift), it is preferable to use the transformer
$T_{1}$.

The second example is found when considering the codensity monad ($\text{Cod}^{F,\bullet}$).
That monad is defined using an arbitrary type constructor $F$. When
$F$ is itself a monad, we see that $\text{Cod}^{F,\bullet}$ is a
new monad that includes the effects of $F$ (Statement~\ref{subsec:Statement-codensity-monad-inC-outC}).
So, we could view $\text{Cod}^{F,\bullet}$ as a monad transformer
applied to a foreign monad $F$. What is the base monad for that monad
transformer? We expect the base monad to be obtained as $\text{Cod}^{F,\bullet}$
with $F=\text{Id}$; this gives $\text{Cod}^{\text{Id},\bullet}=\text{Id}^{\bullet}$
(see proof of Statement~\ref{subsec:Statement-codensity-monad-inC-outC}).
So, the codensity type constructor is an alternative transformer \emph{for
the identity monad}. The identity monad also has a standard transformer,
$T_{\text{Id}}^{M,A}\triangleq M^{A}$. 

\subsubsection{Statement \label{subsec:Statement-codensity-monad-3}\ref{subsec:Statement-codensity-monad-3} }

The type constructor $\text{Cod}^{M,\bullet}$ is a transformer for
the identity monad ($\text{Id}$) applied to the foreign monad $M$.
The transformer is incomplete as it lacks a foreign runner, and its
base runner fails the composition law of monad morphisms.

\subparagraph{Proof}

The monad laws hold because $\text{Cod}^{M,\bullet}$ is a monad (Statement~\ref{subsec:Statement-codensity-monad-lawful}). 

To verify the identity laws: when $M=\text{Id}$, we have (by the
Yoneda identity):
\[
\text{Cod}^{\text{Id},A}=\forall R.\,(A\rightarrow R)\rightarrow R\cong A=\text{Id}^{A}\quad.
\]

The foreign lift method is defined as the monad morphism \lstinline!inC!
(Statement~\ref{subsec:Statement-codensity-monad-inC-outC}).

A foreign runner is not possible since $\text{Cod}^{M,\bullet}$ is
not covariant in $M$. 

A base runner should have type signature $\text{Cod}^{M,A}\rightarrow M^{A}$.
This is implemented by the function \lstinline!outC! from Statement~\ref{subsec:Statement-codensity-monad-inC-outC}.
However, the proof of that statement shows that \lstinline!outC!
does not satisfy the monad morphism composition law.

\section{Further developments}

\subsection{Some properties of monad morphisms}

In this section we prove some properties of monad morphisms used elsewhere
in this chapter.

\subsubsection{Statement \label{subsec:Statement-M-to-M-times-M-is-monadic-morphism}\ref{subsec:Statement-M-to-M-times-M-is-monadic-morphism}}

For any monad $M$, the function $\Delta:M^{A}\rightarrow M^{A}\times M^{A}$
is a monad morphism between monads $M$ and $M\times M$.

\subparagraph{Proof}

We use the definition of the product monad. The method $\text{pu}_{M\times M}$
is defined by
\[
x\triangleright\text{pu}_{M\times M}=\text{pu}_{M}(x)\times\text{pu}_{M}(x)=x\triangleright\text{pu}_{M}\bef\Delta\quad,
\]
which proves the identity law for $\Delta$ (namely, $\text{pu}_{M}\bef\Delta=\text{pu}_{M\times M}$).
To verify $\Delta$\textsf{'}s composition law, 
\[
\text{ftn}_{M}\bef\Delta=\Delta^{\uparrow M}\bef\Delta\bef\text{ftn}_{M\times M}\quad,
\]
we use the definition~(\ref{eq:monad-product-flatten-def-ftn}) of
$\text{ftn}_{M\times M}$:
\[
\text{ftn}_{M\times M}:M^{M^{\bullet}\times M^{\bullet}}\times M^{M^{\bullet}\times M^{\bullet}}\rightarrow M^{\bullet}\times M^{\bullet}=\big(\pi_{1}^{\uparrow M}\bef\text{ftn}_{M}\big)\boxtimes\big(\pi_{2}^{\uparrow M}\bef\text{ftn}_{M}\big)\quad,
\]
and compute:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{ftn}_{M}\bef\Delta:}\quad & \gunderline{\Delta^{\uparrow M}\bef\Delta}\bef\text{ftn}_{M\times M}\\
{\color{greenunder}\text{naturality law of }\Delta:}\quad & =\Delta\bef\big(\Delta^{\uparrow M}\boxtimes\Delta^{\uparrow M}\big)\bef\gunderline{\text{ftn}_{M\times M}}\\
{\color{greenunder}\text{definition of }\text{ftn}_{M\times M}:}\quad & =\Delta\bef\big(\Delta^{\uparrow M}\boxtimes\Delta^{\uparrow M}\big)\bef\big(\pi_{1}^{\uparrow M}\bef\text{ftn}_{M}\big)\boxtimes\big(\pi_{2}^{\uparrow M}\bef\text{ftn}_{M}\big)\\
{\color{greenunder}\text{composition law of }\boxtimes:}\quad & =\Delta\bef\big(\gunderline{\Delta^{\uparrow M}\bef\pi_{1}^{\uparrow M}}\bef\text{ftn}_{M}\big)\boxtimes\big(\gunderline{\Delta^{\uparrow M}\bef\pi_{2}^{\uparrow M}}\bef\text{ftn}_{M}\big)\\
{\color{greenunder}\text{simplify }\Delta\bef\pi_{i}=\text{id}:}\quad & =\Delta\bef\text{ftn}_{M}\boxtimes\text{ftn}_{M}\\
{\color{greenunder}\text{duplication law of }\Delta:}\quad & =\text{ftn}_{M}\bef\Delta\quad.
\end{align*}


\subsubsection{Statement \label{subsec:Statement-pair-product-of-monadic-morphisms}\ref{subsec:Statement-pair-product-of-monadic-morphisms}}

For any monads $K$, $L$, $M$, $N$ and monad morphisms $\phi:K\leadsto M$
and $\chi:L\leadsto N$, the pair product $\phi\boxtimes\chi:K\times L\leadsto M\times N$
is a monad morphism between the monads $K\times L$ and $M\times N$.

\subparagraph{Proof}

The definitions of $\text{pu}_{K\times L}$ and $\text{pu}_{M\times N}$
are
\[
\text{pu}_{K\times L}=\text{pu}_{K}\boxtimes\text{pu}_{L}\quad,\quad\quad\text{pu}_{M\times N}=\text{pu}_{M}\boxtimes\text{pu}_{N}\quad.
\]

To verify the identity law for $\phi\boxtimes\chi$:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{pu}_{M\times N}:}\quad & \gunderline{\text{pu}_{K\times L}}\bef\phi\boxtimes\chi\\
{\color{greenunder}\text{definition of }\text{pu}_{K\times L}:}\quad & =\text{pu}_{K}\boxtimes\text{pu}_{L}\bef\phi\boxtimes\chi\\
{\color{greenunder}\text{composition law of }\boxtimes:}\quad & =(\gunderline{\text{pu}_{K}\bef\phi})\boxtimes(\gunderline{\text{pu}_{L}\bef\chi})\\
{\color{greenunder}\text{identity laws of }\phi,\chi:}\quad & =\text{pu}_{M}\boxtimes\text{pu}_{N}=\text{pu}_{M\times N}\quad.
\end{align*}

To verify the composition law for $\phi\boxtimes\chi$, we use the
definitions 
\begin{align*}
 & \text{ftn}_{K\times L}=\big(\pi_{1}^{\uparrow K}\bef\text{ftn}_{K}\big)^{:K^{K^{\bullet}\times L^{\bullet}}\rightarrow K^{\bullet}}\boxtimes\big(\pi_{2}^{\uparrow L}\bef\text{ftn}_{L}\big)^{:L^{K^{\bullet}\times L^{\bullet}}\rightarrow L^{\bullet}}\quad,\\
 & \text{ftn}_{M\times N}=\big(\pi_{1}^{\uparrow M}\bef\text{ftn}_{M}\big)\boxtimes\big(\pi_{2}^{\uparrow N}\bef\text{ftn}_{N}\big)\quad.
\end{align*}
Denote $\psi\triangleq\phi\boxtimes\chi$ for brevity. The required
law is
\[
\text{ftn}_{K\times L}\bef\psi=\psi^{\uparrow(K\times L)}\bef\psi\bef\text{ftn}_{M\times N}\quad.
\]
The left-hand side of this law is
\begin{align*}
 & \text{ftn}_{K\times L}\bef\psi\\
{\color{greenunder}\text{definition of }\text{ftn}_{M\times N}:}\quad & =\big(\pi_{1}^{\uparrow K}\bef\text{ftn}_{K}\big)\boxtimes\big(\pi_{2}^{\uparrow L}\bef\text{ftn}_{L}\big)\bef\phi\boxtimes\chi\\
{\color{greenunder}\text{composition law of }\boxtimes:}\quad & =\big(\pi_{1}^{\uparrow K}\bef\text{ftn}_{K}\bef\phi\big)\boxtimes\big(\pi_{2}^{\uparrow L}\bef\text{ftn}_{L}\bef\chi\big)
\end{align*}
The right-hand side is
\begin{align*}
 & \gunderline{\psi^{\uparrow(K\times L)}}\bef\psi\bef\text{ftn}_{M\times N}\\
{\color{greenunder}\text{lifting to }K\times L:}\quad & =\big(\psi^{\uparrow K}\boxtimes\psi^{\uparrow L}\big)\bef(\phi\boxtimes\chi)\bef\gunderline{\text{ftn}_{M\times N}}\\
{\color{greenunder}\text{definition of }\text{ftn}_{M\times N}:}\quad & =\psi^{\uparrow K}\boxtimes\psi^{\uparrow L}\bef\phi\boxtimes\chi\bef\big(\pi_{1}^{\uparrow M}\bef\text{ftn}_{M}\big)\boxtimes\big(\pi_{2}^{\uparrow N}\bef\text{ftn}_{N}\big)\\
{\color{greenunder}\text{composition law of }\boxtimes:}\quad & =\big(\psi^{\uparrow K}\bef\phi\bef\pi_{1}^{\uparrow M}\bef\text{ftn}_{M}\big)\boxtimes\big(\psi^{\uparrow L}\bef\chi\bef\pi_{2}^{\uparrow N}\bef\text{ftn}_{N}\big)\quad.
\end{align*}
Now rewrite the first part of the pair product in the last line:
\begin{align*}
 & \gunderline{\psi^{\uparrow K}\bef\phi}\bef\pi_{1}^{\uparrow M}\bef\text{ftn}_{M}\\
{\color{greenunder}\text{naturality law of }\phi:}\quad & =\phi\bef\gunderline{\psi^{\uparrow M}\bef\pi_{1}^{\uparrow M}}\bef\text{ftn}_{M}\\
{\color{greenunder}\text{projection law of }\pi_{1}:}\quad & =\gunderline{\phi\bef\pi_{1}^{\uparrow M}}\bef\phi^{\uparrow M}\bef\text{ftn}_{M}\\
{\color{greenunder}\text{naturality law of }\phi:}\quad & =\pi_{1}^{\uparrow K}\bef\gunderline{\phi\bef\phi^{\uparrow M}\bef\text{ftn}_{M}}\\
{\color{greenunder}\text{composition law of }\phi:}\quad & =\pi_{1}^{\uparrow K}\bef\text{ftn}_{K}\bef\phi\quad.
\end{align*}
In the same way, we find that the second part of the pair product
is $\pi_{2}^{\uparrow L}\bef\text{ftn}_{L}\bef\chi$, and so the composition
law holds.

\subsubsection{Statement \label{subsec:Statement-projection-is-monadic-morphism}\ref{subsec:Statement-projection-is-monadic-morphism}}

For any monads $M$ and $N$, the projection function $\pi_{1}:M\times N\leadsto M$
is a monad morphism. Same for $\pi_{2}:M\times N\leadsto N$.

\subparagraph{Proof}

It is sufficient to verify the laws for $\pi_{1}$; the proof for
$\pi_{2}$ will be similar. The identity law:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{pu}_{M}:}\quad & \text{pu}_{M\times N}\bef\pi_{1}\\
{\color{greenunder}\text{definition of }\text{pu}_{M\times N}:}\quad & =(\text{pu}_{M}\boxtimes\text{pu}_{N})\bef\pi_{1}\\
{\color{greenunder}\text{projection law of }\pi_{1}:}\quad & =\text{pu}_{M}\quad.
\end{align*}
The composition law:
\begin{align*}
{\color{greenunder}\text{expect to equal }\pi_{1}\bef\pi_{1}^{\uparrow M}\bef\text{ftn}_{M}:}\quad & \gunderline{\text{ftn}_{M\times N}}\bef\pi_{1}\\
{\color{greenunder}\text{definition of }\text{ftn}_{M\times N}:}\quad & =\gunderline{\big(\pi_{1}^{\uparrow M}\bef\text{ftn}_{M}\big)}\boxtimes\big(\pi_{2}^{\uparrow N}\bef\text{ftn}_{N}\big)\bef\gunderline{\pi_{1}}\\
{\color{greenunder}\text{projection law of }\pi_{1}:}\quad & =\pi_{1}\bef\pi_{1}^{\uparrow M}\bef\text{ftn}_{M}\quad.
\end{align*}


\subsubsection{Statement \label{subsec:Statement-product-swap-is-monadic-morphism}\ref{subsec:Statement-product-swap-is-monadic-morphism}}

For any monads $M$ and $N$, the swapping function $\sigma:M\times N\leadsto N\times M$
is a monad morphism.

\subparagraph{Proof}

The code for $\sigma$ can be written as a combination of other functions:
$\sigma=\Delta\bef\left(\pi_{2}\boxtimes\pi_{1}\right)$. The functions
$\Delta$, $\pi_{1}$, and $\pi_{2}$ are monad morphisms by Statements~\ref{subsec:Statement-M-to-M-times-M-is-monadic-morphism}
and~\ref{subsec:Statement-projection-is-monadic-morphism}. The function
product $\pi_{1}\boxtimes\pi_{2}$ is a monad morphism by Statement~\ref{subsec:Statement-pair-product-of-monadic-morphisms}.
So $\sigma$ is a composition of monad morphisms; by Statement~\ref{subsec:Statement-monadic-morphism-composition},
$\sigma$ is a monad morphism.

\subsection{Does a composition of rigid monads have a \texttt{swap} function?\label{subsec:Does-a-composition-have-swap}}

In Section~\ref{subsec:Rigid-monad-construction-1-choice}, we proved
the monad transformer laws for $T_{R}^{M}\triangleq R\circ M$ by
using a \lstinline!swap! function with type signature
\[
\text{sw}_{R,M}:M\circ R\leadsto R\circ M\quad,
\]
and proving its special laws. If $R$ and $S$ are both rigid monads
then the composed monad $R\circ S$ is also rigid. Does $T\triangleq R\circ S$
have a suitable \lstinline!swap! function,
\[
\text{sw}_{T,M}:M\circ R\circ S\leadsto R\circ S\circ M\quad,
\]
satisfying all the required special laws of \lstinline!swap!? If
so, we may be able to find a simpler definition of \lstinline!flatten!
for the monad stack $R\circ S\circ M$. Let us briefly investigate
this question. However, keep in mind that the absence of a suitable
\lstinline!swap! function will not invalidate the composition properties
of rigid monad stacks: those properties were established without assuming
the existence of \lstinline!swap! for the composed monad.

It turns out that we need yet another law for \lstinline!swap! (the
\textsf{``}3-swap\textsf{''} law) if we wish to prove that the composed monad also
has a lawful \lstinline!swap!. 

\subsubsection{Statement \label{subsec:Statement-3-swap-law}\ref{subsec:Statement-3-swap-law}}

Assume that two monads $R$ and $S$ are rigid and both have \lstinline!swap!
functions ($\text{sw}_{R,M}$ and $\text{sw}_{S,M}$) satisfying the
$8$ laws listed in Statements~\ref{sec:Statement-swap-laws-to-monad-transformer-first-law}
and~\ref{subsec:Statement-outside-transformer-swap-laws}. Additionally,
assume that%
\begin{comment}
precarious formatting
\end{comment}

\begin{wrapfigure}{l}{0.4\columnwidth}%
\vspace{-2\baselineskip}

\[
\xymatrix{\xyScaleY{1.5pc}\xyScaleX{2pc}M^{S^{R^{A}}}\ar[d]\sb(0.45){\text{sw}_{S,M}}\ar[r]\sp(0.5){\text{sw}_{R,S}^{\uparrow M}} & M^{R^{S^{A}}}\ar[r]\sp(0.5){\text{sw}_{R,M}} & R^{M^{S^{A}}}\ar[d]\sp(0.4){\text{sw}_{S,M}^{\uparrow R}}\\
S^{M^{R^{A}}}\ar[r]\sp(0.5){\text{sw}_{R,M}^{\uparrow S}} & S^{R^{M^{A}}}\ar[r]\sp(0.5){\text{sw}_{R,S}} & R^{S^{M^{A}}}
}
\]
\vspace{-1.4\baselineskip}

\[
\xymatrix{\xyScaleY{1.5pc}\xyScaleX{3pc}M\circ R\circ S\ar[rd]\sb(0.45){\text{sw}_{T,M}\triangleq}\ar[r]\sp(0.5){\text{sw}_{R,M}} & R\circ M\circ S\ar[d]\sp(0.5){\text{sw}_{S,M}^{\uparrow R}}\\
 & R\circ S\circ M
}
\]
\vspace{-0.8\baselineskip}
\end{wrapfigure}%

\noindent the functions $\text{sw}_{R,M}$ and $\text{sw}_{S,M}$
obey the \textbf{3-swap law\index{monads!3-swap law}} with respect
to an arbitrary monad $M$:
\begin{equation}
\text{sw}_{R,S}^{\uparrow M}\bef\text{sw}_{R,M}\bef\text{sw}_{S,M}^{\uparrow R}=\text{sw}_{S,M}\bef\text{sw}_{R,M}^{\uparrow S}\bef\text{sw}_{R,S}\quad.\label{eq:rigid-monad-3-swap-law}
\end{equation}
Then a \lstinline!swap! function ($\text{sw}_{T,M}$) also exists
for the composed monad $T\triangleq R\circ S$ and is defined by 
\begin{equation}
\text{sw}_{T,M}\triangleq\text{sw}_{R,M}\bef\text{sw}_{S,M}^{\uparrow R}\quad,\label{eq:3-swap-def-of-sw-T-M}
\end{equation}
and satisfies the same $8$ laws.

\paragraph{Proof}

We need to verify the $8$ laws for $\text{sw}_{T,M}$ (one naturality
law, two identity laws, two interchange laws, and three monadic naturality
laws), assuming that these $8$ laws hold for $\text{sw}_{R,M}$ and
$\text{sw}_{S,M}$. In addition, we assume that Eq.~(\ref{eq:rigid-monad-3-swap-law})
holds, where $M$ is an arbitrary monad. The monad methods of $T$
are defined by Eqs.~(\ref{eq:def-pure-T-via-pure-L-and-pure-M})\textendash (\ref{eq:def-flatten-T-via-sw-and-flatten-L-M})
after renaming $L\triangleq R$ and $M\triangleq S$:
\begin{align}
\text{pu}_{T} & =\text{pu}_{S}\bef\text{pu}_{R}\quad,\label{eq:3-swap-pu-T-via-pu-R-S}\\
\text{ftn}_{T} & =\text{sw}_{R,S}^{\uparrow R}\bef\text{ftn}_{R}\bef\text{ftn}_{S}^{\uparrow R}\quad.\label{eq:3-swap-ftn-T-via-sw-R-S}
\end{align}

As usual, we do not need to verify the naturality law for $\text{sw}_{T,M}$.

\paragraph{Identity laws}

To verify the outer identity law:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{pu}_{T}:}\quad & \text{pu}_{T}^{\uparrow M}\bef\text{sw}_{T,M}\\
{\color{greenunder}\text{use Eqs.~(\ref{eq:3-swap-def-of-sw-T-M})-(\ref{eq:3-swap-pu-T-via-pu-R-S})}:}\quad & =\text{pu}_{S}^{\uparrow M}\bef\gunderline{\text{pu}_{R}^{\uparrow M}\bef\text{sw}_{R,M}}\bef\text{sw}_{S,M}^{\uparrow R}\\
{\color{greenunder}\text{outer identity law of }\text{sw}_{R,M}:}\quad & =\text{pu}_{S}^{\uparrow M}\bef\gunderline{\text{pu}_{R}\bef\text{sw}_{S,M}^{\uparrow R}}\\
{\color{greenunder}\text{naturality law of }\text{pu}_{R}:}\quad & =\gunderline{\text{pu}_{S}^{\uparrow M}\bef\text{sw}_{S,M}}\bef\text{pu}_{R}\\
{\color{greenunder}\text{outer identity law of }\text{sw}_{S,M}:}\quad & =\text{pu}_{S}\bef\text{pu}_{R}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:3-swap-pu-T-via-pu-R-S})}:}\quad & =\text{pu}_{T}\quad.
\end{align*}
To verify the inner identity law:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{pu}_{M}^{\uparrow T}:}\quad & \text{pu}_{M}\bef\gunderline{\text{sw}_{T,M}}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:3-swap-def-of-sw-T-M})}:}\quad & =\gunderline{\text{pu}_{M}\bef\text{sw}_{R,M}}\bef\text{sw}_{S,M}^{\uparrow R}\\
{\color{greenunder}\text{inner identity law of }\text{sw}_{R,M}:}\quad & =\text{pu}_{M}^{\uparrow R}\bef\text{sw}_{S,M}^{\uparrow R}=\big(\gunderline{\text{pu}_{M}\bef\text{sw}_{S,M}}\big)^{\uparrow R}\\
{\color{greenunder}\text{inner identity law of }\text{sw}_{S,M}:}\quad & =\text{pu}_{M}^{\gunderline{\uparrow S\uparrow R}}=\text{pu}_{M}^{\uparrow T}\quad.
\end{align*}


\paragraph{Interchange laws}

The outer interchange law is
\begin{equation}
\text{ftn}_{T}^{\uparrow M}\bef\text{sw}_{T,M}=\text{sw}_{T,M}\bef\text{sw}_{T,M}^{\uparrow T}\bef\text{ftn}_{T}\quad.\label{eq:3-swap-outer-interchange-T}
\end{equation}
We will use the outer interchange laws for $\text{sw}_{R,M}$ and
$\text{sw}_{S,M}$:
\begin{align}
 & \text{ftn}_{R}^{\uparrow M}\bef\text{sw}_{R,M}=\text{sw}_{R,M}\bef\text{sw}_{R,M}^{\uparrow R}\bef\text{ftn}_{R}\quad,\label{eq:3-swap-outer-interchange-R}\\
 & \text{ftn}_{S}^{\uparrow M}\bef\text{sw}_{S,M}=\text{sw}_{S,M}\bef\text{sw}_{S,M}^{\uparrow S}\bef\text{ftn}_{S}\quad.\label{eq:3-swap-outer-interchange-S}
\end{align}
Begin with the right-hand side of Eq.~(\ref{eq:3-swap-outer-interchange-T})
since it is more complicated:
\begin{align*}
 & \text{sw}_{T,M}\bef\text{sw}_{T,M}^{\uparrow T}\bef\text{ftn}_{T}\\
{\color{greenunder}\text{definitions}:}\quad & =\text{sw}_{R,M}\bef\gunderline{\text{sw}_{S,M}^{\uparrow R}\bef\big(\text{sw}_{R,M}\bef\text{sw}_{S,M}^{\uparrow R}\big)^{\uparrow S\uparrow R}\bef\text{sw}_{R,S}^{\uparrow R}}\bef\text{ftn}_{R}\bef\text{ftn}_{S}^{\uparrow R}\\
{\color{greenunder}^{\uparrow R}\text{-composition}:}\quad & =\text{sw}_{R,M}\bef\big(\text{sw}_{S,M}\bef\text{sw}_{R,M}^{\uparrow S}\bef\gunderline{\text{sw}_{S,M}^{\uparrow R\uparrow S}\bef\text{sw}_{R,S}}\big)^{\uparrow R}\bef\text{ftn}_{R}\bef\text{ftn}_{S}^{\uparrow R}\\
{\color{greenunder}\text{naturality law of }\text{sw}_{R,S}:}\quad & =\text{sw}_{R,M}\bef\big(\gunderline{\text{sw}_{S,M}\bef\text{sw}_{R,M}^{\uparrow S}\bef\text{sw}_{R,S}}\bef\text{sw}_{S,M}^{\uparrow S\uparrow R}\big)^{\uparrow R}\bef\text{ftn}_{R}\bef\text{ftn}_{S}^{\uparrow R}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:rigid-monad-3-swap-law})}:}\quad & =\text{sw}_{R,M}\bef\big(\gunderline{\text{sw}_{R,S}^{\uparrow M}\bef\text{sw}_{R,M}\bef\text{sw}_{S,M}^{\uparrow R}}\bef\text{sw}_{S,M}^{\uparrow S\uparrow R}\big)^{\uparrow R}\bef\text{ftn}_{R}\bef\text{ftn}_{S}^{\uparrow R}\quad.
\end{align*}
In the last expression, all \lstinline!flatten!s are to the right
of all \lstinline!swap!s. So we look to rewrite the left-hand side
of Eq.~(\ref{eq:3-swap-outer-interchange-T}) into the same form:
\begin{align*}
 & \text{ftn}_{T}^{\uparrow M}\bef\text{sw}_{T,M}\\
{\color{greenunder}\text{use Eqs.~(\ref{eq:3-swap-def-of-sw-T-M}), (\ref{eq:3-swap-ftn-T-via-sw-R-S})}:}\quad & =\big(\text{sw}_{R,S}^{\uparrow R}\bef\text{ftn}_{R}\bef\gunderline{\text{ftn}_{S}^{\uparrow R}\big)^{\uparrow M}\bef\text{sw}_{R,M}}\bef\text{sw}_{S,M}^{\uparrow R}\\
{\color{greenunder}\text{naturality law of }\text{sw}_{R,M}:}\quad & =\text{sw}_{R,S}^{\uparrow R\uparrow M}\bef\gunderline{\text{ftn}_{R}^{\uparrow M}\bef\text{sw}_{R,M}}\bef\text{ftn}_{S}^{\uparrow M\uparrow R}\bef\text{sw}_{S,M}^{\uparrow R}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:3-swap-outer-interchange-R})}:}\quad & =\text{sw}_{R,S}^{\uparrow R\uparrow M}\bef\text{sw}_{R,M}\bef\text{sw}_{R,M}^{\uparrow R}\bef\text{ftn}_{R}\bef\big(\gunderline{\text{ftn}_{S}^{\uparrow M}\bef\text{sw}_{S,M}}\big)^{\uparrow R}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:3-swap-outer-interchange-S})}:}\quad & =\text{sw}_{R,M}\bef\text{sw}_{R,S}^{\uparrow M\uparrow R}\bef\text{sw}_{R,M}^{\uparrow R}\bef\gunderline{\text{ftn}_{R}\bef\big(\text{sw}_{S,M}\bef\text{sw}_{S,M}^{\uparrow S}}\bef\text{ftn}_{S}\big)^{\uparrow R}\\
{\color{greenunder}\text{naturality law of }\text{ftn}_{R}:}\quad & =\text{sw}_{R,M}\bef\gunderline{\text{sw}_{R,S}^{\uparrow M\uparrow R}\bef\text{sw}_{R,M}^{\uparrow R}\bef\big(\text{sw}_{S,M}\bef\text{sw}_{S,M}^{\uparrow S}\big)^{\uparrow R\uparrow R}}\bef\text{ftn}_{R}\bef\text{ftn}_{S}^{\uparrow R}\\
{\color{greenunder}\text{composition under }^{\uparrow R}:}\quad & =\text{sw}_{R,M}\bef\big(\gunderline{\text{sw}_{R,S}^{\uparrow M}\bef\text{sw}_{R,M}\bef\text{sw}_{S,M}^{\uparrow R}\bef\text{sw}_{S,M}^{\uparrow S\uparrow R}}\big)^{\uparrow R}\bef\text{ftn}_{R}\bef\text{ftn}_{S}^{\uparrow R}\quad.
\end{align*}
Both sides of the outer interchange law~(\ref{eq:3-swap-outer-interchange-T})
are now equal.

The proof of the inner interchange law is simpler: the law says
\begin{equation}
\text{ftn}_{M}\bef\text{sw}_{T,M}=\text{sw}_{T,M}^{\uparrow M}\bef\text{sw}_{T,M}\bef\text{ftn}_{M}^{\uparrow T}\quad.\label{eq:3-swap-inner-interchange-T}
\end{equation}
We will use the inner interchange laws for $\text{sw}_{R,M}$ and
$\text{sw}_{S,M}$:
\begin{align}
 & \text{ftn}_{M}\bef\text{sw}_{R,M}=\text{sw}_{R,M}^{\uparrow M}\bef\text{sw}_{R,M}\bef\text{ftn}_{M}^{\uparrow R}\quad,\label{eq:3-swap-inner-interchange-R}\\
 & \text{ftn}_{M}\bef\text{sw}_{S,M}=\text{sw}_{S,M}^{\uparrow M}\bef\text{sw}_{S,M}\bef\text{ftn}_{M}^{\uparrow S}\quad.\label{eq:3-swap-inner-interchange-S}
\end{align}
Begin with the left-hand side of Eq.~(\ref{eq:3-swap-inner-interchange-T}):
\begin{align*}
 & \text{ftn}_{M}\bef\text{sw}_{T,M}=\gunderline{\text{ftn}_{M}\bef\text{sw}_{R,M}}\bef\text{sw}_{S,M}^{\uparrow R}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:3-swap-inner-interchange-R})}:}\quad & =\text{sw}_{R,M}^{\uparrow M}\bef\text{sw}_{R,M}\bef\gunderline{\text{ftn}_{M}^{\uparrow R}\bef\text{sw}_{S,M}^{\uparrow R}}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:3-swap-inner-interchange-S}) under }^{\uparrow R}:}\quad & =\text{sw}_{R,M}^{\uparrow M}\bef\text{sw}_{R,M}\bef\gunderline{\big(\text{sw}_{S,M}^{\uparrow M}\bef\text{sw}_{S,M}\bef\text{ftn}_{M}^{\uparrow S}\big)^{\uparrow R}}\\
{\color{greenunder}\text{composition under }^{\uparrow R}:}\quad & =\text{sw}_{R,M}^{\uparrow M}\bef\text{sw}_{R,M}\bef\gunderline{\text{sw}_{S,M}^{\uparrow M\uparrow R}\bef\text{sw}_{S,M}^{\uparrow R}\bef\text{ftn}_{M}^{\uparrow S\uparrow R}}
\end{align*}
The right-hand side of Eq.~(\ref{eq:3-swap-inner-interchange-T})
is 
\begin{align*}
 & \text{sw}_{T,M}^{\uparrow M}\bef\text{sw}_{T,M}\bef\text{ftn}_{M}^{\uparrow T}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:3-swap-def-of-sw-T-M})}:}\quad & =\big(\text{sw}_{R,M}\bef\gunderline{\text{sw}_{S,M}^{\uparrow R}\big)^{\uparrow M}\bef\text{sw}_{R,M}}\bef\text{sw}_{S,M}^{\uparrow R}\bef\text{ftn}_{M}^{\uparrow S\uparrow R}\\
{\color{greenunder}\text{naturality law of }\text{sw}_{R,M}:}\quad & =\text{sw}_{R,M}^{\uparrow M}\bef\gunderline{\text{sw}_{R,M}\bef\text{sw}_{S,M}^{\uparrow M\uparrow R}}\bef\text{sw}_{S,M}^{\uparrow R}\bef\text{ftn}_{M}^{\uparrow S\uparrow R}\quad.
\end{align*}
The right-hand side is now equal to the left-hand side.

\paragraph{Monadic naturality laws}

We need to verify that the following three laws,
\[
\text{sw}_{T,\text{Id}}=\text{id}\quad,\quad\quad\text{sw}_{T,M}\bef\phi^{\uparrow T}=\phi\bef\text{sw}_{T,N}\quad,\quad\quad\text{sw}_{T,M}\bef\theta=\theta^{\uparrow M}\quad,
\]
hold for any monad morphisms $\phi:M\leadsto N$ and $\theta:T\leadsto\text{Id}$.
We may assume that these laws already hold for $\text{sw}_{R,M}$
and $\text{sw}_{S,M}$.

To verify the first law, write
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{id}:}\quad & \text{sw}_{T,\text{Id}}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:3-swap-def-of-sw-T-M})}:}\quad & =\text{sw}_{R,\text{Id}}\bef\text{sw}_{S,\text{Id}}^{\uparrow R}\\
{\color{greenunder}\text{first law of }\text{sw}_{R,\text{Id}}\text{ and }\text{sw}_{S,\text{Id}}:}\quad & =\text{id}\bef\text{id}^{\uparrow R}=\text{id}\quad.
\end{align*}
To verify the second law, write
\begin{align*}
{\color{greenunder}\text{expect to equal }\phi\bef\text{sw}_{T,N}:}\quad & \text{sw}_{T,M}\bef\phi^{\uparrow T}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:3-swap-def-of-sw-T-M})}:}\quad & =\text{sw}_{R,M}\bef\gunderline{\text{sw}_{S,M}^{\uparrow R}\bef\phi^{\uparrow S\uparrow R}}\\
{\color{greenunder}\text{second law of }\text{sw}_{S,M}\text{ under }^{\uparrow R}:}\quad & =\gunderline{\text{sw}_{R,M}\bef\big(\phi}\bef\text{sw}_{S,N}\big)^{\uparrow R}\\
{\color{greenunder}\text{second law of }\text{sw}_{R,M}:}\quad & =\phi\bef\gunderline{\text{sw}_{R,N}\bef\text{sw}_{S,N}^{\uparrow R}}=\phi\bef\gunderline{\text{sw}_{T,N}}\quad.
\end{align*}
To verify the third law, we begin with the left-hand side:
\[
\text{sw}_{T,M}\bef\theta=\text{sw}_{R,M}\bef\text{sw}_{S,M}^{\uparrow R}\bef\theta\quad.
\]
At this point, no relationship or law applies to the intermediate
expression $\text{sw}_{S,M}^{\uparrow R}\bef\theta$, so we need additional
information to proceed. By Statement~\ref{subsec:Statement-base-runner-for-composed-monad}
(proved below), we can express $\theta=\theta_{R}\bef\theta_{S}$
with some monad morphisms $\theta_{R}$ and $\theta_{S}$. So, we
may use $\theta_{R}$ and $\theta_{S}$ with the monad morphism laws
for $R$ and $S$, in particular with the third law:
\[
\text{sw}_{R,M}\bef\theta_{R}=\theta_{R}^{\uparrow M}\quad,\quad\quad\text{sw}_{S,M}\bef\theta_{S}=\theta_{S}^{\uparrow M}\quad.
\]
This allows us to finish the proof of the third monadic naturality
law:
\begin{align*}
{\color{greenunder}\text{expect to equal }\theta^{\uparrow M}:}\quad & \text{sw}_{T,M}\bef\gunderline{\theta}\\
{\color{greenunder}\text{use Statement~\ref{subsec:Statement-base-runner-for-composed-monad}}:}\quad & =\text{sw}_{R,M}\bef\gunderline{\text{sw}_{S,M}^{\uparrow R}\bef\theta_{R}}\bef\theta_{S}\\
{\color{greenunder}\text{naturality law of }\theta_{R}:}\quad & =\gunderline{\text{sw}_{R,M}\bef\theta_{R}}\bef\gunderline{\text{sw}_{S,M}\bef\theta_{S}}\\
{\color{greenunder}\text{third law of }R\text{ and }S:}\quad & =\theta_{R}^{\uparrow M}\bef\theta_{S}^{\uparrow M}=\theta^{\uparrow M}\quad.
\end{align*}


\subsubsection{Statement \label{subsec:Statement-base-runner-for-composed-monad}\ref{subsec:Statement-base-runner-for-composed-monad}}

Let $R$ be a rigid monad with a lawful \lstinline!swap! method $\text{sw}_{R,M}$.
Let $S$ be any monad. Then any monad morphism $\theta:R\circ S\leadsto\text{Id}$
can be expressed as $\theta=\theta_{R}\bef\theta_{S}$ by defining
the functions
\[
\theta_{R}\triangleq\text{pu}_{S}^{\uparrow R}\bef\theta\quad,\quad\quad\theta_{S}\triangleq\text{pu}_{R}\bef\theta\quad,
\]
which are monad morphisms. So, any runner $\theta$ for the composed
monad $R\circ S$ can be written as a function composition of some
runners $\theta_{R}:R\leadsto\text{Id}$ and $\theta_{S}:S\leadsto\text{Id}$
for the monads $R$ and $S$. 

\paragraph{Proof}

How can we obtain $\theta_{R}$ and $\theta_{S}$ from the given runner
$\theta$? Note that $\theta$ runs the operations of both monads
$R$ and $S$, while $\theta_{R}$ runs only the operations of $R$.
To obtain $\theta_{R}:R\leadsto\text{Id}$ from $\theta:R\circ S\leadsto\text{Id}$,
we need to prepend a function of type $R\leadsto R\circ S$. A suitable
function of that type is 
\[
\text{pu}_{S}^{\uparrow R}:R^{A}\rightarrow R^{S^{A}}\quad.
\]
So, $\theta_{R}=\text{pu}_{S}^{\uparrow R}\bef\theta$ has the correct
type signature, $R^{A}\rightarrow A$. Similarly, $\theta_{S}=\text{pu}_{R}\bef\theta$
has the correct type signature, $S^{A}\rightarrow A$. So, we can
obtain $\theta_{R}$ and $\theta_{S}$ from the given runner $\theta$
as
\[
\theta_{R}\triangleq\text{pu}_{S}^{\uparrow R}\bef\theta\quad,\quad\quad\theta_{S}\triangleq\text{pu}_{R}\bef\theta\quad.
\]
Since $\text{pu}_{R}$ and $\text{pu}_{S}^{\uparrow R}$ are the foreign
and base lifts of the transformer $T_{R}^{S}=R\circ S$, Statement~\ref{subsec:Statement-outside-transformer-swap-laws}
shows that $\text{pu}_{R}$ and $\text{pu}_{S}^{\uparrow R}$ are
monad morphisms. Since the composition of monad morphisms is again
a monad morphism (Statement~\ref{subsec:Statement-monadic-morphism-composition}),
we see that $\theta_{R}$ and $\theta_{S}$ are monad morphisms.

It remains to verify that $\theta=\theta_{R}\bef\theta_{S}$:
\begin{align*}
{\color{greenunder}\text{expect to equal }\theta:}\quad & \theta_{R}\bef\theta_{S}=\text{pu}_{S}^{\uparrow R}\bef\gunderline{\theta\bef\text{pu}_{R}}\bef\theta\\
{\color{greenunder}\text{naturality law of }\theta:}\quad & =\text{pu}_{S}^{\uparrow R}\bef\text{pu}_{R}^{\gunderline{\uparrow T}}\bef\theta\bef\theta=\text{pu}_{S}^{\uparrow R}\bef\text{pu}_{R}^{\uparrow S\uparrow R}\bef\gunderline{\theta\bef\theta}\\
{\color{greenunder}\text{composition law of }\theta:}\quad & =\text{pu}_{S}^{\uparrow R}\bef\text{pu}_{R}^{\uparrow S\uparrow R}\bef\gunderline{\text{ftn}_{T}\bef\theta}\quad.
\end{align*}
The last line differs from the required result ($\theta$) by the
function $\text{pu}_{S}^{\uparrow R}\bef\text{pu}_{R}^{\uparrow S\uparrow R}\bef\text{ftn}_{T}$.
We will finish the proof if we show that this function is equal to
an identity function:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{id}:}\quad & \text{pu}_{S}^{\uparrow R}\bef\text{pu}_{R}^{\uparrow S\uparrow R}\bef\gunderline{\text{ftn}_{T}}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:def-flatten-T-via-sw-and-flatten-L-M})}:}\quad & =\text{pu}_{S}^{\uparrow R}\bef\gunderline{\text{pu}_{R}^{\uparrow S\uparrow R}\bef\text{sw}_{R,S}^{\uparrow R}}\bef\text{ftn}_{R}\bef\text{ftn}_{S}^{\uparrow R}\\
{\color{greenunder}\text{outer-identity law of }\text{sw}_{R,S}:}\quad & =\text{pu}_{S}^{\uparrow R}\bef\gunderline{\text{pu}_{R}^{\uparrow R}\bef\text{ftn}_{R}}\bef\text{ftn}_{S}^{\uparrow R}\\
{\color{greenunder}\text{identity laws of }R\text{ and }S:}\quad & =\gunderline{\text{pu}_{S}^{\uparrow R}\bef\text{ftn}_{S}^{\uparrow R}}=\text{id}\quad.
\end{align*}


\subsection{Rigid functors and their properties\label{subsec:Rigid-functors}}

Some properties of rigid monads can be extended to a (possibly) larger
class of rigid functors. We begin with a definition of a rigid functor
that, unlike the definition of rigid monads (Section~\ref{sec:transformers-rigid-monads}),
does not refer to monad transformers.

\paragraph{Definition }

A functor $R$ is \textbf{rigid}\index{rigid functor} if there exists
a natural transformation \lstinline!fuseIn! (denoted by $\text{fi}_{R}$)
with type signature
\[
\text{fi}_{R}:(A\rightarrow R^{B})\rightarrow R^{A\rightarrow B}
\]
satisfying the non-degeneracy law~(\ref{eq:rigid-non-degeneracy-law})
shown below.

Not all functors admit a natural transformation with the type signature
of \lstinline!fuseIn!. For example, the functor $F^{A}\triangleq Z+A$
is not rigid because the required type signature 
\[
\text{fi}:\left(A\rightarrow Z+B\right)\rightarrow Z+\left(A\rightarrow B\right)
\]
cannot be implemented. However, any functor $R$ admits the opposite
natural transformation \lstinline!fuseOut! (denoted by $\text{fo}_{R}$):
\begin{equation}
\text{fo}:R^{A\rightarrow B}\rightarrow A\rightarrow R^{B}\quad,\quad\quad\text{fo}\left(r\right)\triangleq a\rightarrow r\triangleright\big(f^{:A\rightarrow B}\rightarrow f\left(a\right)\big)^{\uparrow R}\quad.\label{eq:fuseOut-def}
\end{equation}
The method \lstinline!fuseIn! must satisfy the nondegeneracy law
\begin{equation}
\text{fi}_{R}\bef\text{fo}_{R}=\text{id}^{:(A\rightarrow R^{B})\rightarrow(A\rightarrow R^{B})}\quad.\label{eq:rigid-non-degeneracy-law}
\end{equation}
The opposite relation does not hold in general: $\text{fo}_{R}\bef\text{fi}_{R}\neq\text{id}$
(see Example~\ref{subsec:Example-fo-fi-not-id}).

The next two statements show some use cases for rigid functors. 

The first use case is a generalization of \lstinline!flatMap! that
can handle multiple $M$-effects at once. As a motivation, consider
a given value $m^{:M^{A}}$ and two Kleisli functions having the same
type signature, $f_{1}:A\rightarrow M^{B}$ and $f_{2}:A\rightarrow M^{B}$.
We may apply $\text{flm}_{M}(f_{1})$ and $\text{flm}_{M}(f_{2})$
to $m$ and obtain two different values of type $M^{B}$. This computation
can be written as
\[
\big(m\triangleright\text{flm}_{M}(f_{1})\big)\times\big(m\triangleright\text{flm}_{M}(f_{2})\big):M^{B}\times M^{B}\quad.
\]
To express this computation in a different but equivalent way, we
define a new function $f$ as 
\[
f:A\rightarrow M^{B}\times M^{B}\quad,\quad\quad f\triangleq\Delta\bef(f_{1}\boxtimes f_{2})\quad,
\]
and a new \textsf{``}double-valued \lstinline!flatMap!\textsf{''} as 
\[
\text{flm2}_{M}:(A\rightarrow M^{B}\times M^{B})\rightarrow M^{A}\rightarrow M^{B}\times M^{B}\quad,\quad\text{flm2}_{M}\triangleq f\rightarrow\Delta\bef\big(\text{flm}_{M}(f\bef\pi_{1})\boxtimes\text{flm}_{M}(f\bef\pi_{2})\big)\quad.
\]
It is clear that the same computation can be extended to a product
of any number of $M$\textsf{'}s. The general version of the \textsf{``}multi-valued
\lstinline!flatMap!\textsf{''} is a situation when the collection of $M$-effects
is described by a rigid functor $R$. The example just shown corresponds
to $R^{A}\triangleq A\times A$.

\subsubsection{Statement \label{subsec:Statement-rigid-functor-multi-flatMap}\ref{subsec:Statement-rigid-functor-multi-flatMap}}

For any rigid functor $R$ and a monad $M$, there exists an \textsf{``}$R$-valued
\lstinline!flatMap!\textsf{''}:
\[
\text{rflm}_{M,R}:(A\rightarrow R^{M^{B}})\rightarrow M^{A}\rightarrow R^{M^{B}}\quad.
\]


\subparagraph{Proof}

Using $R$\textsf{'}s \lstinline!fuseIn! method, we can convert a value of
type $A\rightarrow R^{M^{B}}$ into a value of type $R^{A\rightarrow M^{B}}$.
After that, we can use $M$\textsf{'}s \lstinline!flatMap!:
\[
\text{rflm}_{M,R}\triangleq k^{:A\rightarrow R^{M^{B}}}\rightarrow m^{:M^{A}}\rightarrow k\triangleright\text{fi}_{R}\triangleright\big(q^{:A\rightarrow M^{B}}\rightarrow m\triangleright\text{flm}_{M}(q)\big)^{\uparrow R}\quad.
\]
This code does not assume that $R$ is a rigid monad. $\square$

The second use case is a program transformation that introduces a
wrapper into a given program. Assume that $p^{:C}$ is an expression
that uses a function $f^{:A\rightarrow B}$, and we would like to
replace $f$ by a function $g^{:A\rightarrow R^{B}}$. We may imagine
that $g$ performs a computation similar to $f$ except it wraps the
results in the functor $R$ (for instance, returning several results
or using concurrency). Can we obtain a transformed program $q:R^{C}$
that has the same functionality as $p$ except for also returning
a value wrapped in $R$? This is possible if $R$ is a rigid functor:

\subsubsection{Statement \label{subsec:Statement-rigid-functor-monadic-refactor}\ref{subsec:Statement-rigid-functor-monadic-refactor}}

Given a rigid functor $R$, a program transformation can be implemented:
\[
\text{refactor}:((A\rightarrow B)\rightarrow C)\rightarrow(A\rightarrow R^{B})\rightarrow R^{C}\quad.
\]
This function transforms a program $p(f^{:A\rightarrow B}):C$ into
a program $q(g^{:A\rightarrow R^{B}}):R^{C}$.

\subparagraph{Proof}

We use $R$\textsf{'}s method \lstinline!fuseIn! to convert a value of type
$A\rightarrow R^{B}$ into a value of type $R^{A\rightarrow B}$.
The rest of the computation is lifted to the functor $R$:
\[
\text{refactor}\triangleq p^{:\left(A\rightarrow B\right)\rightarrow C}\rightarrow k^{:A\rightarrow R^{B}}\rightarrow k\triangleright\text{fi}_{R}\triangleright p^{\uparrow R}\quad.
\]

$\square$

For a rigid functor $R$, the type signature of $\text{fi}_{R}$ is
the same as the type signature of \lstinline!swap! with respect to
the \lstinline!Reader! monad,
\[
\text{sw}_{R,M}:M^{R^{A}}\rightarrow R^{M^{A}}\cong(Z\rightarrow R^{A})\rightarrow R^{Z\rightarrow A}\quad\text{ if we set }\quad M^{A}\triangleq Z\rightarrow A\quad.
\]
All rigid monads considered in Section~\ref{sec:transformers-rigid-monads}
have a \lstinline!swap! method. It turns out that all rigid monads
(regardless of the existence of \lstinline!swap!) are also rigid
functors. While proving that statement, we will directly use the definition
of rigid monads via the composed-outside monad transformer, without
assuming a \lstinline!swap! method.

\subsubsection{Statement \label{subsec:Statement-rigid-monads-are-rigid-functors}\ref{subsec:Statement-rigid-monads-are-rigid-functors}}

A rigid monad $R$ is a rigid functor.

\subparagraph{Proof}

By assumption, the monad $R$ has a composed-outside monad transformer
$T_{R}^{M}=R\circ M$ and the corresponding method $\text{ftn}_{T}$.
We can define the transformation $\text{fi}_{R}$ in the same way
as Eq.~(\ref{eq:define-swap-via-flatten}) defined the \lstinline!swap!
method via $\text{ftn}_{T}$. To use that formula, we need to set
the foreign monad $M$ to be the \lstinline!Reader! monad, $M^{B}\triangleq A\rightarrow B$,
with a fixed environment type $A$:

\begin{wrapfigure}{l}{0.4\columnwidth}%
\vspace{-1.9\baselineskip}

\[
\xymatrix{\xyScaleY{1.5pc}\xyScaleX{4pc}(A\rightarrow R^{B})\ar[r]\sp(0.5){\text{pu}_{M}^{\uparrow R\uparrow M}}\ar[d]\sb(0.5){\text{fi}_{R}\triangleq} & (A\rightarrow R^{A\rightarrow B})\ar[d]\sp(0.5){\text{pu}_{R}}\\
R^{A\rightarrow B} & R^{A\rightarrow R^{A\rightarrow B}}\ar[l]\sb(0.5){\text{ftn}_{T}}
}
\]
\vspace{-0.8\baselineskip}
\end{wrapfigure}%

~\vspace{-0.4\baselineskip}
\begin{equation}
\text{fi}_{R}(f^{:A\rightarrow R^{B}})=\text{pu}_{M}^{\uparrow R\uparrow M}\bef\text{pu}_{R}\bef\text{ftn}_{T}\quad.\label{eq:rigid-monad-fuseIn-def}
\end{equation}
Since $M$ is the \lstinline!Reader! monad with the environment type
$A$, we define $\text{pu}_{M}$ and $f^{\uparrow M}$ by
\[
\text{pu}_{M}(x)=(\_^{:A}\rightarrow x)\quad,\quad\quad r^{:A\rightarrow X}\triangleright(f^{:X\rightarrow Y})^{\uparrow M}=r\bef f\quad.
\]
The type signature of the function \lstinline!fuseOut!,
\[
\text{fo}:R^{A\rightarrow B}\rightarrow A\rightarrow R^{B}\quad,
\]
resembles \textsf{``}running\textsf{''} the composed monad $R^{M^{B}}$ into $R^{B}$,
consuming a value of type $A$. Indeed, given a fixed value $a^{:A}$,
we can \textsf{``}run\textsf{''} the \lstinline!Reader! monad into the identity monad.
The corresponding runner $\phi_{a}^{:M\leadsto\text{Id}}$ is
\begin{equation}
\phi_{a}^{:M^{X}\rightarrow X}\triangleq m^{:A\rightarrow X}\rightarrow m(a)\quad.\label{eq:runner-phi-def}
\end{equation}
So we are inspired to use the runner law for the monad transformer
$T_{R}^{M}$. That law (which holds since we assumed that $T_{R}^{M}$
satisfies all laws) says that the lifted runner $\phi_{a}^{\uparrow R}$
is a monad morphism $T_{R}^{M}\leadsto T_{R}^{\text{Id}}\cong T_{R}^{M}\leadsto R$.
The monad morphism law for $\phi_{a}^{\uparrow R}$ is then written
as
\begin{equation}
\text{ftn}_{T}\bef\phi_{a}^{\uparrow R}=\phi_{a}^{\uparrow R\uparrow M\uparrow R}\bef\phi_{a}^{\uparrow R}\bef\text{ftn}_{R}\quad.\label{eq:rigid-monad-is-rigid-functor-derivation1}
\end{equation}
How could we use this law to obtain Eq.~(\ref{eq:rigid-non-degeneracy-law})?
Compare Eqs.~(\ref{eq:fuseOut-def}) and~(\ref{eq:runner-phi-def})
and derive the connection between the runner $\phi_{a}$ and the \lstinline!fuseOut!
function (which exists for any functor $R$):
\[
\text{fo}_{R}=r\rightarrow a\rightarrow r\triangleright\phi_{a}^{\uparrow R}\quad.
\]
Then we can complete the derivation by rewriting the law~(\ref{eq:rigid-non-degeneracy-law}):
\begin{align*}
{\color{greenunder}\text{expect to equal }m:}\quad & m^{:M^{R^{B}}}\triangleright\text{fi}_{R}\bef\text{fo}_{R}=\left(m\triangleright\text{fi}_{R}\right)\triangleright\gunderline{\text{fo}_{R}}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:fuseOut-def})}:}\quad & =a\rightarrow m\triangleright\gunderline{\text{fi}_{R}}\triangleright\phi_{a}^{\uparrow R}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:rigid-monad-fuseIn-def})}:}\quad & =a\rightarrow m\triangleright\text{pu}_{M}^{\uparrow R\uparrow M}\bef\text{pu}_{R}\bef\gunderline{\text{ftn}_{T}\bef\phi_{a}^{\uparrow R}}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:rigid-monad-is-rigid-functor-derivation1})}:}\quad & =a\rightarrow m\triangleright\text{pu}_{M}^{\uparrow R\uparrow M}\bef\gunderline{\text{pu}_{R}\bef\phi_{a}^{\uparrow R\uparrow M\uparrow R}\bef\phi_{a}^{\uparrow R}}\bef\text{ftn}_{R}\\
{\color{greenunder}\text{naturality law of }\text{pu}_{R}:}\quad & =a\rightarrow m\triangleright\text{pu}_{M}^{\uparrow R\uparrow M}\bef\phi_{a}^{\uparrow R\uparrow M}\bef\phi_{a}\bef\gunderline{\text{pu}_{R}\bef\text{ftn}_{R}}\\
{\color{greenunder}\text{left identity law of }R:}\quad & =a\rightarrow m\triangleright\gunderline{(\text{pu}_{M}\bef\phi_{a})}^{\uparrow R\uparrow M}\bef\phi_{a}\\
{\color{greenunder}\text{monad morphism identity law of }\phi_{a}:}\quad & =a\rightarrow m\triangleright\gunderline{\phi_{a}}\\
{\color{greenunder}\text{definition~(\ref{eq:runner-phi-def}) of }\phi_{a}:}\quad & =a\rightarrow m(a)=m\quad.
\end{align*}
Here we used the monad morphism identity law for $\phi_{a}$:
\[
\text{pu}_{M}\bef\phi_{a}=\big(x\rightarrow(\_\rightarrow x)\big)\bef(m\rightarrow a\triangleright m)=\left(x\rightarrow a\triangleright(\_\rightarrow x)\right)=\left(x\rightarrow x\right)=\text{id}\quad.
\]


\subsubsection{Example \label{subsec:Example-fo-fi-not-id}\ref{subsec:Example-fo-fi-not-id}\index{solved examples}}

Show that the functions \lstinline!fuseIn! and \lstinline!fuseOut!
are not always inverses: for some $R$,
\[
\text{fo}_{R}\bef\text{fi}_{R}\neq\text{id}\quad.
\]


\subparagraph{Solution}

Consider the rigid monads $P^{A}\triangleq Z\rightarrow A$ and $R^{A}\triangleq\left(A\rightarrow Q\right)\rightarrow A$,
where $Q$ and $Z$ are fixed types. Since all rigid monads are rigid
functors, it follows that the monads $P$ and $R$ have methods $\text{fi}_{P}$,
$\text{fo}_{P}$, $\text{fi}_{R}$, $\text{fo}_{R}$ satisfying the
non-degeneracy law~(\ref{eq:rigid-non-degeneracy-law}). It turns
out that additionally $\text{fo}_{P}\bef\text{fi}_{P}=\text{id}$,
i.e., the methods $\text{fo}_{P}$ and $\text{fi}_{P}$ \emph{are}
inverses of each other, but $\text{fo}_{R}\bef\text{fi}_{R}\neq\text{id}$.

To show that $\text{fo}_{P}\bef\text{fi}_{P}=\text{id}$, consider
the type signatures of $\text{fo}_{P}$ and $\text{fi}_{P}$:
\begin{align*}
\text{fo}_{P} & :P^{A\rightarrow B}\rightarrow A\rightarrow P^{B}\cong\left(Z\rightarrow A\rightarrow B\right)\rightarrow\left(A\rightarrow Z\rightarrow B\right)\quad,\\
\text{fi}_{P} & :(A\rightarrow P^{B})\rightarrow P^{A\rightarrow B}\cong\left(A\rightarrow Z\rightarrow B\right)\rightarrow\left(Z\rightarrow A\rightarrow B\right)\quad.
\end{align*}
Fully parametric implementations of these functions are derived uniquely
from type signatures. The functions $\text{fo}_{P}$ and $\text{fi}_{P}$
switch the curried arguments of types $A$ and $Z$ of a function
that returns values of type $B$. It is clear that these two functions
are inverses of each other. To show this directly, consider the type
signature of $\text{fo}_{P}\bef\text{fi}_{P}$,
\[
\big(\text{fo}_{P}\bef\text{fi}_{P}\big):P^{A\rightarrow B}\rightarrow P^{A\rightarrow B}\cong\left(Z\rightarrow A\rightarrow B\right)\rightarrow\left(Z\rightarrow A\rightarrow B\right)\quad.
\]
There is only one fully parametric implementation for this type signature:
the identity function $\text{id}^{Z\rightarrow A\rightarrow B}$.

For the monad $R$, the type signatures of $\text{fi}_{R}$ and $\text{fo}_{R}$
are
\begin{align*}
\text{fi}_{R} & :\left(A\rightarrow\left(B\rightarrow Q\right)\rightarrow B\right)\rightarrow\left(\left(A\rightarrow B\right)\rightarrow Q\right)\rightarrow A\rightarrow B\quad,\\
\text{fo}_{R} & :\left(\left(\left(A\rightarrow B\right)\rightarrow Q\right)\rightarrow A\rightarrow B\right)\rightarrow A\rightarrow\left(B\rightarrow Q\right)\rightarrow B\quad.
\end{align*}
The implementations are again derived uniquely from type signatures:
\begin{align*}
 & \text{fi}_{R}\big(f^{:A\rightarrow\left(B\rightarrow Q\right)\rightarrow B}\big)=x^{:\left(A\rightarrow B\right)\rightarrow Q}\rightarrow a^{:A}\rightarrow f(a)(b^{:B}\rightarrow x(\_\rightarrow b))\quad,\\
 & \text{fo}_{R}\big(g^{:\left(\left(A\rightarrow B\right)\rightarrow Q\right)\rightarrow A\rightarrow B}\big)=a^{:A}\rightarrow y^{:B\rightarrow Q}\rightarrow g(h^{:A\rightarrow B}\rightarrow y(h(a)))(a)\quad.
\end{align*}
We notice that the implementation of $\text{fi}_{R}$ uses a constant
function, $\left(\_\rightarrow b\right)$, which is likely to lose
information. Indeed, while $\text{fi}_{R}\bef\text{fo}_{R}=\text{id}$
as it must be due to the rigid non-degeneracy law, we find:
\begin{align*}
{\color{greenunder}\text{expect \emph{not} to equal }g:}\quad & g\triangleright\text{fo}_{R}\bef\text{fi}_{R}=\left(g\triangleright\text{fo}_{R}\right)\triangleright\gunderline{\text{fi}_{R}}\\
{\color{greenunder}\text{definition of }\text{fi}_{R}:}\quad & =x\rightarrow a\rightarrow\gunderline{\text{fo}_{R}}(g)(a)(b\rightarrow x(\_\rightarrow b))\\
{\color{greenunder}\text{definition of }\text{fo}_{R}:}\quad & =x\rightarrow a\rightarrow g\big(h^{:A\rightarrow B}\rightarrow h(a)\triangleright\gunderline{(b\rightarrow}\,x(\_\rightarrow b))\big)(a)\\
{\color{greenunder}\text{apply to argument }b:}\quad & =x\rightarrow a\rightarrow g\big(h\rightarrow x(\_\rightarrow h(a))\big)(a)\quad.
\end{align*}
We cannot simplify the last line any further: the functions $g$,
$h$, and $x$ are unknown, and we cannot calculate symbolically,
say, the value of $x(\_\rightarrow h(a))$. If the last line were
equal to $g$, we would expect it to be $x\rightarrow a\rightarrow g(x)(a)$.
The difference is in the first argument of $g$: we have $h\rightarrow x(\_\rightarrow h(a))$
instead of $x$. The two last expressions are not always equal; they
would be equal if we had 
\[
\left(h\rightarrow x(h)\right)=\left(h\rightarrow x(k\rightarrow h(k))\right)
\]
instead of $h\rightarrow x(\_\rightarrow h(a))$. Consider again the
argument of $x$ in the two last expressions: $k\rightarrow h(a)$
instead of $k\rightarrow h(k)$. Since $h$ is not always a constant
function ($h$ is an arbitrary function of type $A\rightarrow B$),
the two expressions $k\rightarrow h(a)$ and $k\rightarrow h(k)$
are generally not equal. So, we must conclude that $\text{fo}_{R}\bef\text{fi}_{R}\neq\text{id}$.
$\square$

Since all rigid monads are rigid functors, we can reuse all the rigid
monad constructions to obtain new rigid functors. The following statement
shows a construction of rigid functors that does not assume any monadic
properties. 

\subsubsection{Statement \label{subsec:Statement-rigid-functor-h-p}\ref{subsec:Statement-rigid-functor-h-p}}

The functor $S^{\bullet}\triangleq H^{\bullet}\rightarrow P^{\bullet}$
is rigid when $H$ is any contrafunctor and $P$ is any rigid functor.
(Note that $P$ does not need to be a monad.)

\subparagraph{Proof}

We assume that $\text{fi}_{P}$ and $\text{fo}_{P}$ are known and
satisfy the non-degeneracy law~(\ref{eq:rigid-non-degeneracy-law}).
The function $\text{fi}_{S}$ is then defined by
\begin{align*}
\text{fi}_{S} & :\big(A\rightarrow H^{B}\rightarrow P^{B}\big)\rightarrow H^{A\rightarrow B}\rightarrow P^{A\rightarrow B}\quad,\\
\text{fi}_{S} & \triangleq f^{:A\rightarrow H^{B}\rightarrow P^{B}}\rightarrow h^{:H^{A\rightarrow B}}\rightarrow\text{fi}_{P}\big(a\rightarrow f(a)\big(h\triangleright(b\rightarrow\_\rightarrow b)^{\downarrow H}\big)\big)\quad,
\end{align*}
or equivalently, using the pipe notation:
\[
h\triangleright\text{fi}_{S}(f)=\big(a\rightarrow h\triangleright\left(b\rightarrow\_\rightarrow b\right)^{\downarrow H}\triangleright f(a)\big)\triangleright\text{fi}_{P}\quad.
\]
Let us write the definition of $\text{fo}_{S}$ as well:
\begin{align*}
\text{fo}_{S} & :\big(H^{A\rightarrow B}\rightarrow P^{A\rightarrow B}\big)\rightarrow A\rightarrow H^{B}\rightarrow P^{B}\quad,\\
\text{fo}_{S} & \triangleq g^{:H^{A\rightarrow B}\rightarrow P^{A\rightarrow B}}\rightarrow a^{:A}\rightarrow h^{:H^{B}}\rightarrow\text{fo}_{P}\big(g\big(h\triangleright(p^{:A\rightarrow B}\rightarrow p(a))^{\downarrow H}\big)\big)(a)\quad,
\end{align*}
or equivalently, using the pipe notation:
\[
\text{fo}_{S}(g)=a\triangleright\big(h\triangleright\left(p\rightarrow p(a)\right)^{\downarrow H}\bef g\bef\text{fo}_{P}\big)\quad.
\]
To verify the non-degeneracy law for $S$, apply both sides to some
arguments; we expect $f\triangleright(\text{fi}_{S}\bef\text{fo}_{S})$
to equal $f$ for an arbitrary $f:A\rightarrow H^{B}\rightarrow P^{B}$.
To compare values, we need to apply both sides further to some arguments
$a:A$ and $h:H^{B}$. So we expect the following expression to equal
$f(a)(h)$:
\begin{align*}
\quad & \left(f\triangleright\text{fi}_{S}\bef\text{fo}_{S}\right)(a)(h)=(f\triangleright\text{fi}_{S}\triangleright\gunderline{\text{fo}_{S}})(a)(h)\\
{\color{greenunder}\text{expand }\text{fo}_{S}:}\quad & =a\triangleright\big(h\triangleright\left(p\rightarrow a\triangleright p\right)^{\downarrow H}\triangleright\gunderline{\text{fi}_{S}(f)}\triangleright\text{fo}_{P}\big)\\
{\color{greenunder}\text{expand }\text{fi}_{S}:}\quad & =a\triangleright\big(\big(a\rightarrow h\triangleright\gunderline{\left(p\rightarrow p(a)\right)^{\downarrow H}\bef\left(b\rightarrow\_\rightarrow b\right)^{\downarrow H}}\bef f(a)\big)\triangleright\text{fi}_{P}\triangleright\text{fo}_{P}\big)\\
{\color{greenunder}\text{compose }^{\downarrow H}:}\quad & =a\triangleright\big(\big(a\rightarrow h\triangleright\gunderline{\left((b\rightarrow\_\rightarrow b)\bef(p\rightarrow p(a))\right)^{\downarrow H}}\bef f(a)\big)\triangleright\text{fi}_{P}\,\gunderline{\triangleright}\,\text{fo}_{P}\big)\quad.
\end{align*}
Computing the function composition
\[
(b\rightarrow\_\rightarrow b)\bef(p\rightarrow p(a))=(b\rightarrow(\_\rightarrow b)(a))=(b\rightarrow b)=\text{id}
\]
and using the non-degeneracy law $\text{fi}_{P}\bef\text{fo}_{P}=\text{id}$,
we can simplify further:
\begin{align*}
 & a\triangleright\big(\big(a\rightarrow h\triangleright\gunderline{\left((b\rightarrow\_\rightarrow b)\bef(p\rightarrow p(a))\right)^{\downarrow H}}\bef f(a)\big)\triangleright\text{fi}_{P}\,\gunderline{\triangleright}\,\text{fo}_{P}\big)\\
{\color{greenunder}\text{identity law for }H:}\quad & =a\triangleright\big(\big(a\rightarrow h\triangleright f(a)\big)\triangleright\gunderline{\text{fi}_{P}\bef\text{fo}_{P}}\big)\\
{\color{greenunder}\text{non-degeneracy}:}\quad & =\gunderline{a\triangleright\big(a\rightarrow}\,h\triangleright f(a)\big)=h\triangleright f(a)\quad.
\end{align*}
This equals $f(a)(h)$, as required.%
\begin{comment}
Trying the triangle notation: It seems that $\left(a\triangleright\right)$
is not so useful, we could just write $\left(f\rightarrow f(a)\right)$
instead.
\begin{align*}
\tilde{\text{fi}}\left(f\right) & =f\triangleright\tilde{\text{fi}}=\left(b\rightarrow\_\rightarrow b\right)^{\downarrow H}\bef f\quad,\\
\tilde{\text{fo}}\left(g\right) & =g\triangleright\tilde{\text{fo}}=h\rightarrow a\rightarrow g((a\triangleright)^{\downarrow H}h)a=h\rightarrow a\rightarrow h\triangleright(a\triangleright)^{\downarrow H}\bef g\bef\left(a\triangleright\right)\quad.
\end{align*}
Then
\begin{align*}
 & f\triangleright\tilde{\text{fi}}\triangleright\tilde{\text{fo}}\\
 & =h\rightarrow a\rightarrow h\triangleright(a\triangleright)^{\downarrow H}\bef\left(f\triangleright\tilde{\text{fi}}\right)\bef\left(a\triangleright\right)\\
 & =h\rightarrow a\rightarrow h\triangleright(a\triangleright)^{\downarrow H}\bef\left(b\rightarrow\_\rightarrow b\right)^{\downarrow H}\bef f\bef\left(a\triangleright\right)\\
 & =h\rightarrow a\rightarrow h\triangleright\left(b\rightarrow\_\rightarrow b\bef\left(a\triangleright\right)\right)^{\downarrow H}\bef f\bef\left(a\triangleright\right)\\
 & =h\rightarrow a\rightarrow h\triangleright f\bef\left(a\triangleright\right)=h\rightarrow a\rightarrow h\triangleright f\triangleright\left(a\triangleright\right)\\
 & =h\rightarrow a\rightarrow f(h)(a)=f
\end{align*}
What are the simplification rules?
\begin{align*}
 & a\rightarrow x\triangleright\left(a\triangleright\right)=x\quad,\\
 & a\rightarrow a\triangleright f=f\quad,\\
 & x\triangleright\left(a\triangleright\right)=x(a)=a\triangleright x\quad,\\
 & x\triangleright y\triangleright\left(a\triangleright\right)=a\triangleright\left(x\triangleright y\right)\quad.
\end{align*}
\end{comment}


\subsubsection{Statement \label{subsec:Statement-rigid-functor-is-pointed}\ref{subsec:Statement-rigid-functor-is-pointed}}

A rigid functor $R$ is pointed; the method \lstinline!pure! can
be defined as
\[
\text{pu}_{R}(x^{:A})\triangleq\text{id}^{:R^{A}\rightarrow R^{A}}\triangleright\text{fi}_{R}\triangleright(\_\rightarrow x)^{\uparrow R}\quad.
\]
There is a selected value $\text{wu}_{R}$ of type $R^{\bbnum 1}$
(\textsf{``}wrapped unit\textsf{''}), computed as 
\begin{equation}
\text{wu}_{R}\triangleq\text{pu}_{R}(1)=\text{id}\triangleright\text{fi}_{R}\triangleright(\_\rightarrow1)^{\uparrow R}\quad.\label{eq:rigid-functor-def-of-wrapped-unit}
\end{equation}


\paragraph{Proof}

The method $\text{fi}_{R}:(X\rightarrow R^{Y})\rightarrow R^{X\rightarrow Y}$
with type parameters $X=R^{A}$ and $Y=A$ is applied to the identity
function $\text{id}:R^{A}=R^{A}$, considered as a value of type $X\rightarrow R^{Y}$.
The result is a value
\[
(\text{id}\triangleright\text{fi}_{R}):R^{R^{A}\rightarrow A}\quad.
\]
This is transformed via the lifted constant function $\left(\_\rightarrow x\right)^{\uparrow R}$,
which takes $R^{R^{A}\rightarrow A}$ and returns $R^{A}$. The resulting
code can be written as
\[
\text{pu}_{R}(x^{:A})\triangleq\text{id}\triangleright\text{fi}_{R}\triangleright(\_^{:R^{A}\rightarrow A}\rightarrow x)^{\uparrow R}\quad.
\]
The function $\text{pu}_{R}$ defined in this way is a natural transformation
since $\text{fi}_{R}$ is one. Applying $\text{pu}_{R}$ to a unit
value, we obtain a selected value $\text{wu}_{R}$ of type $R^{\bbnum 1}$.
$\quad$$\square$

The next statement shows that $\text{wu}_{R}$ is the \emph{only}
distinct value of the type $R^{\bbnum 1}$. This means, in particular,
that a rigid functor cannot be a disjunctive type defined with more
than one constructor, such as $\bbnum 1+A$ or $\text{List}^{A}$.
This is the motivation for the name \textsf{``}rigid\textsf{''}: the data structure
$R^{A}$ must have a fixed \textsf{``}shape\textsf{''} and cannot be a disjunction
of several variants. 

\subsubsection{Statement \label{subsec:Statement-rigid-functor-wrapped-unit-is-unit}\ref{subsec:Statement-rigid-functor-wrapped-unit-is-unit}}

If a functor $R$ has a method $\text{fi}_{R}$ satisfying the non-degeneracy
law~(\ref{eq:rigid-non-degeneracy-law}) then the type $R^{\bbnum 1}$
is equivalent to the unit type: $R^{\bbnum 1}\cong\bbnum 1$. The
value $\text{wu}_{R}$ defined by Eq.~(\ref{eq:rigid-functor-def-of-wrapped-unit})
is the only distinct value of type $R^{\bbnum 1}$. The isomorphism
between $\bbnum 1$ and $R^{\bbnum 1}$ is the function $\left(1\rightarrow\text{wu}_{R}\right)$.

\paragraph{Proof}

The trick is to apply both sides of the non-degeneracy law $\text{fi}_{R}\bef\text{fo}_{R}=\text{id}$
to the identity function of type $R^{\bbnum 1}\rightarrow R^{\bbnum 1}$.
To adapt the type parameters, consider the type signature of $\text{fi}_{R}\bef\text{fo}_{R}$:
\[
\big(\text{fi}_{R}\bef\text{fo}_{R}\big):(A\rightarrow R^{B})\rightarrow(A\rightarrow R^{B})\quad,
\]
and set $A=R^{\bbnum 1}$ and $B=\bbnum 1$. The left-hand side of
the law can be now applied to the identity function $\text{id}:R^{\bbnum 1}\rightarrow R^{\bbnum 1}$,
which yields a value of type $R^{\bbnum 1}\rightarrow R^{\bbnum 1}$,
i.e., a function 
\[
f_{1}:R^{\bbnum 1}\rightarrow R^{\bbnum 1}\quad,\quad\quad f_{1}\triangleq\text{fo}_{R}(\text{fi}_{R}(\text{id}))\quad.
\]
We will show that $f_{1}$ is a constant function, $f_{1}=(\_\rightarrow\text{wu}_{R})$,
always returning the same value $\text{wu}_{R}$ defined in Statement~\ref{subsec:Statement-rigid-functor-is-pointed}.
However, the right-hand side of the non-degeneracy law applied to
$\text{id}$ is the identity function of type $R^{\bbnum 1}\rightarrow R^{\bbnum 1}$.
So, the non-degeneracy law means that $f_{1}=\text{id}$. If the identity
function of type $R^{\bbnum 1}\rightarrow R^{\bbnum 1}$ always returns
the same value ($\text{wu}_{R}$), it will mean that $\text{wu}_{R}$
is the only distinct value of the type $R^{\bbnum 1}$.

We note that for any fixed type $A$, the function type $A\rightarrow\bbnum 1$
is equivalent to the unit type ($\bbnum 1$). This is because there
exists only one fully parametric function of type $A\rightarrow\bbnum 1$,
namely $(\_\rightarrow1)$. The code of that function is uniquely
determined by its type signature. In other words, there exists only
one distinct value of the type $A\rightarrow\bbnum 1$, and that value
is $(\_^{:A}\rightarrow1)$. 

The isomorphism between the types $A\rightarrow\bbnum 1$ and $\bbnum 1$
is realized by the functions $u:\bbnum 1\rightarrow A\rightarrow\bbnum 1$
and $v:\left(A\rightarrow\bbnum 1\right)\rightarrow\bbnum 1$. The
code of these functions is also uniquely determined by their type
signatures:
\[
u=\big(1\rightarrow\_^{:A}\rightarrow1\big)\quad,\quad\quad v=\big(\_^{:A\rightarrow\bbnum 1}\rightarrow1\big)\quad.
\]

Applying $\text{fi}_{R}$ to the identity function of type $R^{\bbnum 1}\rightarrow R^{\bbnum 1}$,
we obtain a value $g$, 
\[
g:R^{R^{\bbnum 1}\rightarrow\bbnum 1}\quad,\quad\quad g\triangleq\text{id}\triangleright\text{fi}_{R}\quad.
\]
Since the type $R^{\bbnum 1}\rightarrow\bbnum 1$ is equivalent to
$\bbnum 1$, the type $R^{R^{\bbnum 1}\rightarrow\bbnum 1}$ is equivalent
to $R^{\bbnum 1}$. To use this equivalence explicitly, we need to
lift the isomorphisms $u$ and $v$ into the functor $R$. The isomorphism
will then map $g:R^{R^{\bbnum 1}\rightarrow\bbnum 1}$ to some $g_{1}:R^{\bbnum 1}$
by
\[
g_{1}\triangleq g\triangleright v^{\uparrow R}\quad.
\]
Substituting the definitions of $g$, $v$, and $\text{wu}_{R}$,
we find that actually $g_{1}=\text{wu}_{R}$:
\[
g_{1}=\text{id}\triangleright\text{fi}_{R}\triangleright v^{\uparrow R}=\text{id}\triangleright\text{fi}_{R}\triangleright(\_\rightarrow1)^{\uparrow R}=\text{wu}_{R}\quad.
\]
We can now map $g_{1}$ back to $g$ via the lifted isomorphism $u$:
\begin{align}
g & =g_{1}\triangleright u^{\uparrow R}=\text{wu}_{R}\triangleright u^{\uparrow R}\nonumber \\
{\color{greenunder}\text{definition of }u:}\quad & =\text{wu}_{R}\triangleright\big(1\rightarrow\_\rightarrow1\big)^{\uparrow R}\quad.\label{eq:rigid-functor-derivation1}
\end{align}
Compute $\text{fo}_{R}(g)$ as
\begin{align*}
 & \text{fo}_{R}(g)=g\triangleright\text{fo}_{R}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:fuseOut-def})}:}\quad & =a^{:R^{\bbnum 1}}\rightarrow g\triangleright\big(f^{:A\rightarrow\bbnum 1}\rightarrow f\left(a\right)\big)^{\uparrow R}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:rigid-functor-derivation1})}:}\quad & =a\rightarrow\text{wu}_{R}\triangleright(1\rightarrow\_^{:A}\rightarrow1)^{\uparrow R}\triangleright\big(f^{:A\rightarrow\bbnum 1}\rightarrow f\left(a\right)\big)^{\uparrow R}\\
{\color{greenunder}\text{composition under }^{\uparrow R}:}\quad & =a\rightarrow\text{wu}_{R}\triangleright\big(1\rightarrow(\_^{:A}\rightarrow1)(a)\big)^{\uparrow R}=a\rightarrow\text{wu}_{R}\triangleright(\gunderline{1\rightarrow1})^{\uparrow R}\\
{\color{greenunder}(1\rightarrow1)\text{ is identity}:}\quad & =(a\rightarrow\text{wu}_{R}\triangleright\text{id})=(a^{:R^{\bbnum 1}}\rightarrow\text{wu}_{R})=(\_^{:R^{\bbnum 1}}\rightarrow\text{wu}_{R})\quad.
\end{align*}
So, $\text{fo}_{R}(g)=\text{fo}_{R}(\text{fi}_{R}(\text{id}))$ is
a function of type $R^{\bbnum 1}\rightarrow R^{\bbnum 1}$ that ignores
its argument and always returns the same value $\text{wu}_{R}$.

By virtue of the non-degeneracy law, $\text{fo}_{R}(g)=\text{id}$.
We see that the identity function $\text{id}:R^{\bbnum 1}\rightarrow R^{\bbnum 1}$
always returns the same value $\text{wu}_{R}$. Applying this function
to an arbitrary value $x:R^{\bbnum 1}$, we get
\[
x=x\triangleright\text{id}=x\triangleright\text{fo}_{R}(g)=x\triangleright(\_\rightarrow\text{wu}_{R})=\text{wu}_{R}\quad.
\]
It means that all values of type $R^{\bbnum 1}$ are equal to $\text{wu}_{R}$.
So the function $1\rightarrow\text{wu}_{R}$ is indeed an isomorphism
between the types $\bbnum 1$ and $R^{\bbnum 1}$.

\subsubsection{Statement \label{subsec:Statement-rigid-functor-product}\ref{subsec:Statement-rigid-functor-product}}

The product of rigid functors is a rigid functor.

\subparagraph{Proof}

We assume that two rigid functors $P$ and $Q$ are given, with their
methods $\text{fi}_{P}$ and $\text{fi}_{Q}$ satisfying the non-degeneracy
law. The functor product $R\triangleq P\times Q$ needs its own $\text{fi}_{R}$
method, with the type signature
\[
\text{fi}_{R}:(A\rightarrow P^{B}\times Q^{B})\rightarrow P^{A\rightarrow B}\times Q^{A\rightarrow B}\quad.
\]
To implement $\text{fi}_{R}$, note that the function type $A\rightarrow P\times Q$
is isomorphic to $\left(A\rightarrow P\right)\times\left(A\rightarrow Q\right)$.
The isomorphism is given by a \lstinline!split! function, defined
as
\[
\text{split}:\left(A\rightarrow B\times C\right)\rightarrow\left(A\rightarrow B\right)\times\left(A\rightarrow C\right)\quad,\quad\quad\text{split}\triangleq f^{:A\rightarrow B\times C}\rightarrow(f\bef\pi_{1})\times(f\bef\pi_{2})\quad.
\]
Then the method $\text{fi}_{R}$ is written more concisely:

\[
\text{fi}_{R}\triangleq\text{split}\bef(\text{fi}_{P}\boxtimes\text{fi}_{Q})\quad.
\]
To check the non-degeneracy law ($\text{fi}_{R}\bef\text{fo}_{R}=\text{id}$),
we need the code of $\text{fo}_{R}$. It is convenient to define $\text{fo}_{R}$
via a \lstinline!merge! function:
\[
\text{merge}:\left(A\rightarrow B\right)\times\left(A\rightarrow C\right)\rightarrow A\rightarrow B\times C\quad,\quad\quad\text{merge}\triangleq f^{:A\rightarrow B}\times g^{:A\rightarrow C}\rightarrow a^{:A}\rightarrow f(a)\times g(a)\quad.
\]
The code of $\text{fo}_{R}$ is then written as:
\[
\text{fo}_{R}:P^{A\rightarrow B}\times Q^{A\rightarrow B}\rightarrow A\rightarrow P^{B}\times Q^{B}\quad,\quad\quad\text{fo}_{R}\triangleq(\text{fo}_{P}\boxtimes\text{fo}_{Q})\bef\text{merge}\quad.
\]
The functions \lstinline!split! and \lstinline!merge! are mutual
inverses. Now we can verify the non-degeneracy law:
\begin{align*}
 & \text{fi}_{R}\bef\text{fo}_{R}=\text{split}\bef\gunderline{(\text{fi}_{P}\boxtimes\text{fi}_{Q})\bef(\text{fo}_{P}\boxtimes\text{fo}_{Q})}\bef\text{merge}\\
 & =\text{split}\bef\big((\gunderline{\text{fi}_{P}\bef\text{fo}_{P}})\boxtimes(\gunderline{\text{fi}_{Q}\bef\text{fo}_{Q}})\big)\bef\text{merge}=\text{split}\bef\gunderline{(\text{id}\boxtimes\text{id})}\bef\text{merge}=\text{split}\bef\text{merge}=\text{id}\quad.
\end{align*}


\subsubsection{Statement \label{subsec:Statement-rigid-functor-composition}\ref{subsec:Statement-rigid-functor-composition}}

The composition of rigid functors is a rigid functor.

\subparagraph{Proof}

We will show that the non-degeneracy law ($\text{fi}_{R}\bef\text{fo}_{R}=\text{id}$)
holds for the functor $R^{\bullet}\triangleq P^{Q^{\bullet}}$ as
long as $P$, $Q$ are rigid. Begin by defining the methods $\text{fi}_{R}$
and $\text{fo}_{R}$, assuming that the corresponding methods of $P$,
$Q$ are known and satisfy the non-degeneracy law. We write:
\begin{align*}
 & \text{fi}_{R}:(A\rightarrow P^{Q^{B}})\rightarrow P^{Q^{A\rightarrow B}}\quad,\quad\quad\text{fi}_{R}\triangleq\text{fi}_{P}\bef\text{fi}_{Q}^{\uparrow P}\quad,\\
 & \text{fo}_{R}:P^{Q^{A\rightarrow B}}\rightarrow A\rightarrow P^{Q^{B}}\quad,\quad\quad\text{fo}_{R}\triangleq\text{fo}_{Q}^{\uparrow P}\bef\text{fo}_{P}\quad.
\end{align*}
To verify the non-degeneracy law for $R$:
\[
\text{fi}_{R}\bef\text{fo}_{R}=\text{fi}_{P}\bef\text{fi}_{Q}^{\uparrow P}\bef\text{fo}_{Q}^{\uparrow P}\bef\text{fo}_{P}=\text{fi}_{P}\bef(\gunderline{\text{fi}_{Q}\bef\text{fo}_{Q}})^{\uparrow P}\bef\text{fo}_{P}=\gunderline{\text{fi}_{P}\bef\text{fo}_{P}}=\text{id}\quad.
\]
\begin{comment}
Flip the curried arguments of the function type $A\rightarrow T^{B}\triangleq A\rightarrow H^{M^{B}}\rightarrow M^{B}$,
to obtain $H^{M^{B}}\rightarrow A\rightarrow M^{B}$, and note that
$A\rightarrow M^{B}$ can be mapped to $M^{A\rightarrow B}$ using
$\text{fi}_{M}$. So we can implement $\tilde{\text{fi}}_{T}$ using
$\text{fi}_{M}$:
\begin{align*}
\tilde{\text{fi}}_{T} & :\big(H^{M^{B}}\rightarrow A\rightarrow M^{B}\big)\rightarrow H^{M^{A\rightarrow B}}\rightarrow M^{A\rightarrow B}\\
\tilde{\text{fi}}_{T} & =f\rightarrow h\rightarrow\text{fi}_{M}\left(f\big(\left(b\rightarrow\_\rightarrow b\right)^{\uparrow M\downarrow H}h\big)\right)\\
\tilde{\text{fo}}_{T} & :\left(H^{M^{A\rightarrow B}}\rightarrow M^{A\rightarrow B}\right)\rightarrow H^{M^{B}}\rightarrow A\rightarrow M^{B}\\
\tilde{\text{fo}}_{T} & =g\rightarrow h\rightarrow a\rightarrow\text{fo}_{M}\left(g\big(\left(p^{:A\rightarrow B}\rightarrow p\,a\right)^{\uparrow M\downarrow H}h\big)\right)a
\end{align*}
To show the non-degeneracy law for $T$, compute
\begin{align*}
 & \tilde{\text{fo}}_{T}\left(\tilde{\text{fi}}_{T}f\right)h^{:H^{M^{B}}}a^{:A}\\
\text{insert the definition of }\tilde{\text{fo}}_{T}\text{: }\quad & =\text{fo}_{M}\left(\left(\tilde{\text{fi}}_{T}f\right)\big(\left(p\rightarrow p\,a\right)^{\uparrow M\downarrow H}h\big)\right)a\\
\text{insert the definition of }\tilde{\text{fi}}_{T}\text{: }\quad & =\text{fo}_{M}\left(\text{fi}_{M}\left(f\big(\left(b\rightarrow\_\rightarrow b\right)^{\uparrow M\downarrow H}\left(p\rightarrow p\,a\right)^{\uparrow M\downarrow H}h\big)\right)\right)a\\
\text{non-degeneracy law for }\text{fi}_{M}\text{: }\quad & =f\big(\left(b\rightarrow\_\rightarrow b\right)^{\uparrow M\downarrow H}\left(p\rightarrow p\,a\right)^{\uparrow M\downarrow H}h\big)a\\
\text{composition laws for }M,H\text{: }\quad & =f\big(\left(b\rightarrow\_\rightarrow b\bef p\rightarrow p\,a\right)^{\uparrow M\downarrow H}h\big)a\\
\text{simplify }\text{: }\quad & =f\left(\left(b\rightarrow b\right)^{\uparrow M\downarrow H}h\right)a\\
\text{identity laws for }M,H\text{: }\quad & =f\,h\,a\quad.
\end{align*}
We obtained $\tilde{\text{fo}}_{T}\left(\tilde{\text{fi}}_{T}\,f\right)h\,a=f\,h\,a$.
Therefore the non-degeneracy law $\tilde{\text{fi}}_{T}\bef\tilde{\text{fo}}_{T}=\text{id}$
holds.
\end{comment}


\subsection{Monadically natural lifting of operations (Jaskelioff\textsf{'}s \texttt{Monatron})}

Section~\ref{subsec:Combining-monads-via-mtl-style} showed that
MTL-style programming requires custom code for lifting monad operations
to all supported monad stacks.\index{Mauro Jaskelioff} M.~Jaskelioff\textsf{'}s
\textsf{``}\texttt{Monatron}\textsf{''} library\footnote{See \texttt{\href{https://www.fceia.unr.edu.ar/~mauro/pubs/monatron.pdf}{https://www.fceia.unr.edu.ar/$\sim$mauro/pubs/monatron.pdf}}}\index{Monatron library@\texttt{Monatron} library}
is based on a systematic method that lifts almost all known monad
operations to almost all monad stacks, including stacks that contain
a single monad with an incomplete or missing transformer (such as
\lstinline!Cont! or \lstinline!IO!) located at the deep end of the
stack. This section, based on the methods and results explained in
a paper by M.~Jaskelioff,\footnote{\textsf{``}Modular monad transformers\textsf{''}, see \texttt{\href{https://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.219.5365}{https://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.219.5365}}}
will show how \texttt{Monatron}\textsf{'}s lifting works. 

\paragraph{Common type signatures for operations}

The first step is to transform all effectful operations into a standard
type signature. Looking at Table~\ref{tab:effectful-operations-for-some-monads},
we find that the type signatures of known operations for various monads
$M$ fall into four patterns: 
\begin{enumerate}
\item Type signature $M^{Q}$ or $P\rightarrow M^{Q}$, where $P$ and $Q$
are fixed types.
\item Type signature $\forall A.\,M^{A}$ or $\forall A.\,F^{A}\rightarrow M^{A}$,
where $F$ is a functor that does not depend on $M$.
\item Type signature $\forall A.\,F^{M^{A}}\rightarrow M^{A}$, where $F$
is a functor that does not depend on $M$.
\item A different type signature (the \lstinline!callcc!, \lstinline!collect!,
\lstinline!process!, and \lstinline!filter! operations).
\end{enumerate}
At first glance, the type signatures of different operations appear
to be different and incompatible with each other. However, it turns
out that almost all operations may be converted into a common type
signature of the form $F^{M^{A}}\rightarrow M^{A}$. The following
definition introduces some helpful names:

\subsubsection{Definition \label{subsec:Definition-simple-standard-operation-monatron}\ref{subsec:Definition-simple-standard-operation-monatron}}

For a given monad $M$ and a given functor $F$:

A \textbf{\textsf{``}fixed-type\textsf{''} operation} is a value of type $P\rightarrow M^{Q}$,
where $P$ and $Q$ are fixed types.

A \textbf{\textsf{``}simple\textsf{''} operation} is a natural transformation (\lstinline!sop!)
with type signature
\[
\text{sop}:\forall A.\,F^{A}\rightarrow M^{A}\quad.
\]

A \textbf{\textsf{``}standard\textsf{''} operation} is a natural transformation (\lstinline!op!)
with type signature
\[
\text{op}:\forall A.\,F^{M^{A}}\rightarrow M^{A}\quad.
\]
$\square$

According to this definition, the \lstinline!State! monad\textsf{'}s \lstinline!get!
and \lstinline!set! operations are \textsf{``}fixed-type\textsf{''}, the \lstinline!Either!
monad\textsf{'}s \lstinline!raise! operation is \textsf{``}simple\textsf{''} (with the functor
$F$ defined as the constant functor $F^{A}\triangleq E$), and the
\lstinline!List! monad\textsf{'}s \lstinline!append! operation is \textsf{``}standard\textsf{''}
(with the functor $F^{A}\triangleq A\times A$). 

The following statement shows that the \textsf{``}fixed-type\textsf{''} operations
are a subset of \textsf{``}simple\textsf{''} operations, while the \textsf{``}simple\textsf{''} operations
are a subset of \textsf{``}standard\textsf{''} operations.

\subsubsection{Statement \label{subsec:Statement-simple-standard-operations-monatron}\ref{subsec:Statement-simple-standard-operations-monatron}}

\textbf{(a)} Any \textsf{``}fixed-type\textsf{''} operation $\text{fop}:P\rightarrow M^{Q}$
is  equivalent to a \textsf{``}simple\textsf{''} operation \lstinline!sop! with functor
$F^{A}\triangleq P\times\left(Q\rightarrow A\right)$. The operations
\lstinline!fop! and \lstinline!sop! are related by:
\[
\text{sop}:P\times\left(Q\rightarrow A\right)\rightarrow M^{A}\quad,\quad\text{sop}=p^{:P}\times q^{:Q\rightarrow A}\rightarrow p\triangleright\text{fop}\bef q^{\uparrow M}\quad,\quad\text{fop}=p^{:P}\rightarrow\text{sop}^{Q}(p\times\text{id}^{Q\rightarrow Q})\quad.
\]

\textbf{(b)} Any \textsf{``}standard\textsf{''} operation $\text{op}:F^{M^{A}}\rightarrow M^{A}$
that satisfies the following compatibility law,

\begin{wrapfigure}{l}{0.25\columnwidth}%
\begin{centering}
\vspace{-2.1\baselineskip}
\[
\xymatrix{\xyScaleY{1.2pc}\xyScaleX{2.0pc}F^{M^{M^{A}}}\ar[d]\sb(0.45){\text{ftn}_{M}^{\uparrow F}}\ar[r]\sb(0.5){\text{op}} & M^{M^{A}}\ar[d]\sp(0.45){\text{ftn}_{M}}\\
F^{M^{A}}\ar[r]\sp(0.5){\text{op}} & M^{A}
}
\]
\par\end{centering}
\vspace{-0.6\baselineskip}
\end{wrapfigure}%

~\vspace{-0.35\baselineskip}
\begin{equation}
\text{op}\bef\text{ftn}_{M}=\text{ftn}_{M}^{\uparrow F}\bef\text{op}\quad,\label{eq:monatron-standard-operation-compatibility-law}
\end{equation}
is equivalent to a \textsf{``}simple\textsf{''} operation \lstinline!sop! defined
by
\[
\text{sop}:F^{A}\rightarrow M^{A}\quad,\quad\quad\text{sop}\triangleq\text{pu}_{M}^{\uparrow F}\bef\text{op}\quad,\quad\quad\text{op}=\text{sop}\bef\text{ftn}_{M}\quad.
\]


\subparagraph{Proof}

\textbf{(a)} The type equivalence $P\rightarrow M^{Q}\cong\forall A.\,P\times\left(Q\rightarrow A\right)\rightarrow M^{A}$
is derived by
\begin{align*}
 & \forall A.\,\gunderline{P\times}\left(Q\rightarrow A\right)\rightarrow M^{A}\cong P\rightarrow\gunderline{\forall A.\,\left(Q\rightarrow A\right)\rightarrow M^{A}}\\
{\color{greenunder}\text{covariant Yoneda identity}:}\quad & \cong P\rightarrow M^{Q}\quad.
\end{align*}

\textbf{(b)} We will prove separately the two directions of the isomorphism.

Direction $\text{op}\rightarrow\text{sop}$: Given that a \textsf{``}standard\textsf{''}
operation $\text{op}:F^{M^{A}}\rightarrow M^{A}$ satisfying Eq.~(\ref{eq:monatron-standard-operation-compatibility-law}),
we first define $\text{sop}\triangleq\text{pu}_{M}^{\uparrow F}\bef\text{op}$
and then compute a new \textsf{``}standard\textsf{''} operation $\text{op}^{\prime}\triangleq\text{sop}\bef\text{ftn}_{M}$.
The new operation is then equal to the initial \lstinline!op!:
\begin{align*}
 & \text{op}^{\prime}=\text{sop}\bef\text{ftn}_{M}=\text{pu}^{\uparrow F}\bef\gunderline{\text{op}\bef\text{ftn}_{M}}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:monatron-standard-operation-compatibility-law})}:}\quad & =\gunderline{\text{pu}^{\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}}\bef\text{op}=(\gunderline{\text{pu}\bef\text{ftn}_{M}})^{\uparrow F}=\text{op}\quad.
\end{align*}

Direction $\text{sop}\rightarrow\text{op}$: Given a \textsf{``}simple\textsf{''}
operation $\text{sop}:F^{A}\rightarrow M^{A}$, we first define $\text{op}\triangleq\text{sop}\bef\text{ftn}_{M}$
and then compute a new \textsf{``}simple\textsf{''} operation $\text{sop}^{\prime}\triangleq\text{pu}^{\uparrow F}\bef\text{op}$.
Then show that \lstinline!sop!$^{\prime}$ equals \lstinline!sop!:
\begin{align*}
 & \text{sop}^{\prime}=\text{pu}^{\uparrow F}\bef\text{op}=\gunderline{\text{pu}^{\uparrow F}\bef\text{sop}}\bef\text{ftn}_{M}\\
{\color{greenunder}\text{naturality law of }\text{sop}:}\quad & =\text{sop}\bef\gunderline{\text{pu}^{\uparrow M}\bef\text{ftn}_{M}}=\text{sop}\quad.
\end{align*}
$\square$

All operations shown in Table~\ref{tab:effectful-operations-for-some-monads}
(except \lstinline!callcc!, \lstinline!collect!, \lstinline!process!,
and \lstinline!filter!) are either \textsf{``}fixed-type\textsf{''}, \textsf{``}simple\textsf{''},
or \textsf{``}standard\textsf{''}, and so (by Statement~\ref{subsec:Statement-simple-standard-operations-monatron})
may be equivalently represented by some \textsf{``}standard\textsf{''} operations.
Many operations with a \textsf{``}standard\textsf{''} type signature turn out to be
equivalent to \textsf{``}simple\textsf{''} operations because they satisfy the compatibility
law. 

\subsubsection{Example \label{subsec:Example-list-append-is-simple-operation}\ref{subsec:Example-list-append-is-simple-operation}}

The \lstinline!List! monad\textsf{'}s \lstinline!append! operation has the
type signature of the \textsf{``}standard\textsf{''} form $F^{\text{List}^{A}}\rightarrow\text{List}^{A}$
with $F^{A}\triangleq A\times A$. As shown by Exercise~\ref{subsec:Exercise-flatten-concat-distributive-law},
\lstinline!append! satisfies the compatibility law~(\ref{eq:monatron-standard-operation-compatibility-law}).
So, by Statement~\ref{subsec:Statement-simple-standard-operations-monatron},
\lstinline!append! is equivalent to a \textsf{``}simple\textsf{''} operation \lstinline!sappend!
defined by
\begin{align*}
 & \text{sappend}:A\times A\rightarrow\text{List}^{A}\quad,\quad\quad\text{sappend}\left(a_{1}\times a_{2}\right)\triangleq[a_{1},a_{2}]=\text{pu}_{\text{List}}(a_{1})\pplus\text{pu}_{\text{List}}(a_{2})\quad,\\
 & p^{:\text{List}^{A}}\pplus q^{:\text{List}^{A}}=\text{ftn}_{\text{List}}([p,q])=\left(p\times q\right)\triangleright\text{sappend}\triangleright\text{ftn}_{\text{List}}\quad.
\end{align*}
$\square$

Certain \textsf{``}standard\textsf{''} operations are \emph{not} equivalent to \textsf{``}simple\textsf{''}
ones:

\subsubsection{Example \label{subsec:Example-monatron-flush-operation}\ref{subsec:Example-monatron-flush-operation}}

The \lstinline!Writer! monad\textsf{'}s \lstinline!clear! operation (erasing
the message log) is defined by
\[
\text{clear}:M^{A}\rightarrow M^{A}\cong A\times W\rightarrow A\times W\quad,\quad\quad\text{clear}\triangleq a^{:A}\times\_^{:W}\rightarrow a\times e_{W}\quad.
\]
The type signature $M^{A}\rightarrow M^{A}$ is of the \textsf{``}standard\textsf{''}
form $F^{M^{A}}\rightarrow M^{A}$ with $F^{A}\triangleq A$. However,
\lstinline!clear! does not satisfy the compatibility law~(\ref{eq:monatron-standard-operation-compatibility-law})
and is not equivalent to a \textsf{``}simple\textsf{''} operation. If it were, the
corresponding \textsf{``}simple\textsf{''} operation would be a natural transformation
of type $F^{A}\rightarrow M^{A}\cong A\rightarrow A\times W$. Such
a natural transformation must be implemented as $\text{sop}:a^{:A}\rightarrow a\times w_{0}$
with some fixed value $w_{0}^{:W}$ that is independent of $a$. The
corresponding \textsf{``}standard\textsf{''} operation is 
\[
\text{op}:M^{A}\rightarrow M^{A}\quad,\quad\quad\text{op}\triangleq\text{sop}\bef\text{ftn}_{M}=(a\times w\rightarrow a\times w\times w_{0})\bef\text{ftn}_{M}=a\times w\rightarrow a\times(w\oplus w_{0})\quad.
\]
This operation appends to the log instead of clearing it. $\square$

To build an intuition for the meaning of \textsf{``}simple\textsf{''} and \textsf{``}standard\textsf{''},
consider a \textsf{``}standard\textsf{''} operation $\text{op}:F^{M^{A}}\rightarrow M^{A}$,
where $F^{A}$ contains some values of type $A$ (such as $F^{A}\triangleq A\times A$
as in the \lstinline!List! monad\textsf{'}s \lstinline!append! operation).
A \textsf{``}simple\textsf{''} operation $\text{sop}:F^{A}\rightarrow M^{A}$ computes
a new $M$-effect value from some values of type $A$ without using
any previously given $M$-effect values. A \textsf{``}standard\textsf{''} operation
\lstinline!op! transforms some effectful values of type $M^{A}$
into a new effectful value. If \lstinline!op! were equivalent to
a \textsf{``}simple\textsf{''} operation \lstinline!sop!, we would have $\text{op}=\text{sop}\bef\text{ftn}_{M}$.
It follows that \lstinline!op! computes a new $M$-effect by flattening
some previously given $M$-effects, possibly depending on some values
of type $A$. 

As a heuristic summary, we may say that a \textsf{``}simple\textsf{''} operation creates
new effect values from ordinary, non-effectful values. \textsf{``}Standard\textsf{''}
operations that are equivalent to \textsf{``}simple\textsf{''}operations cannot perform
arbitrary transformations of effects; the given effects must be flattened
and combined with a new effect value, but may not be transformed in
any other way. A \textsf{``}standard\textsf{''} operation could transform effects
in a way that is \emph{not} equivalent to flattening (as the example
with \lstinline!clear! shows).

Putting the \textsf{``}non-standard\textsf{''} operations \lstinline!callcc!, \lstinline!collect!,
\lstinline!process!, and \lstinline!filter! temporarily aside, we
now focus on the methods for lifting \textsf{``}simple\textsf{''} and \textsf{``}standard\textsf{''}
operations to monad stacks.

The goal is to lift a \textsf{``}standard\textsf{''} operation $\text{op}_{M}:F^{M}\leadsto M$
from a monad $M$ to a monad stack $P$ containing $M$. We assume
that a lawful monad morphism $p:M\leadsto P$ is given. We expect
that the new operation, $\text{op}_{P}:F^{P}\leadsto P$, should correctly
perform the functionality of the operation $\text{op}_{M}$ in the
monad $M$ embedded within $P$. 

For example, since the \lstinline!List! monad\textsf{'}s \lstinline!append!
operation appends two lists, we expect that the corresponding lifted
operation ($\text{append}_{P}$) should correctly append lists embedded
within the stack $P$. The \lstinline!Writer! monad\textsf{'}s \lstinline!clear!
operation clears the log, so we expect that the corresponding lifted
operation ($\text{clear}_{P}$) also clears the log embedded within
the stack $P$.

To express this requirement formally, we note that the monad morphism
$p$ correctly embeds the monad methods of $M$ into $P$. So, we
may require that the transformation of effects by \lstinline!op!
should commute with the mapping by $p$. This requirement is written
as a \index{monadic naturality law!of lifted operations}monadic naturality
law:

\begin{wrapfigure}{l}{0.2\columnwidth}%
\begin{centering}
\vspace{-2.1\baselineskip}
\[
\xymatrix{\xyScaleY{1.2pc}\xyScaleX{2.0pc}F^{M^{A}}\ar[d]\sb(0.45){p^{\uparrow F}}\ar[r]\sb(0.5){\text{op}_{M}} & M^{A}\ar[d]\sp(0.45){p}\\
F^{P^{A}}\ar[r]\sp(0.5){\text{op}_{P}} & P^{A}
}
\]
\par\end{centering}
\vspace{0.2\baselineskip}
\end{wrapfigure}%

~\vspace{-0.45\baselineskip}
\begin{equation}
\text{op}_{M}\bef p=p^{\uparrow F}\bef\text{op}_{P}\quad.\label{eq:monatron-monadic-naturality-for-operations}
\end{equation}

\noindent The goal of this section is to derive monadically natural
liftings of operations.

\paragraph{Lifting \textsf{``}simple\textsf{''} operations}

Section~\ref{subsec:Combining-monads-via-mtl-style} showed that
the \lstinline!State! monad\textsf{'}s \lstinline!get! and \lstinline!set!
operations are lifted to any monad stack by composing with a lift
function. This method works %
\begin{comment}
equally well 
\end{comment}
for any \textsf{``}simple\textsf{''} operation $\text{sop}_{M}:F^{A}\rightarrow M^{A}$
in a monad $M$ and an arbitrary monad stack $P$ that has a lift
function $p:M^{A}\rightarrow P^{A}$. The result of lifting is a \textsf{``}simple\textsf{''}
operation ($\text{sop}_{P}$) defined by
\begin{equation}
\text{sop}_{P}:F^{A}\rightarrow P^{A}\quad,\quad\quad\text{sop}_{P}\triangleq\text{sop}_{M}\bef p\quad.\label{eq:monatron-lift-simple-operation}
\end{equation}
The following statement shows how to express this lifting in terms
of \textsf{``}standard\textsf{''} operations. It also proves that the \textsf{``}standard\textsf{''}
counterpart of $\text{sop}_{P}$ always satisfies the monadic naturality
law.

\subsubsection{Statement \label{subsec:Statement-monatron-lifting-simple-operation}\ref{subsec:Statement-monatron-lifting-simple-operation}}

Given a \textsf{``}simple\textsf{''} $M$-operation $\text{sop}_{M}:F^{A}\rightarrow M^{A}$
and a monad morphism $p:M\leadsto P$ between two monads $M$ and
$P$, define the operation $\text{sop}_{P}$ by Eq.~(\ref{eq:monatron-lift-simple-operation}).
Then the \textsf{``}standard\textsf{''} operation $\text{op}_{P}\triangleq\text{sop}_{P}\bef\text{ftn}_{P}$
corresponding to $\text{sop}_{P}$ is expressed via $\text{op}_{M}$
by
\begin{equation}
\text{op}_{P}=\text{pu}_{M}^{\uparrow F}\bef\text{op}_{M}\bef p\bef\text{ftn}_{P}\label{eq:monatron-lifting-simple-op}
\end{equation}
and satisfies the monadic naturality law~(\ref{eq:monatron-monadic-naturality-for-operations}).
Here, we defined $\text{op}_{M}\triangleq\text{sop}_{M}\bef\text{ftn}_{M}$.

\subparagraph{Proof}

We substitute the definitions of $\text{sop}_{P}$ and the relationship
between $\text{sop}_{M}$ and $\text{op}_{M}$:
\[
\text{op}_{P}=\gunderline{\text{sop}_{P}}\bef\text{ftn}_{P}=\gunderline{\text{sop}_{M}}\bef p\bef\text{ftn}_{P}=\text{pu}_{M}^{\uparrow F}\bef\text{op}_{M}\bef p\bef\text{ftn}_{P}\quad.
\]
To verify the monadic naturality law~(\ref{eq:monatron-monadic-naturality-for-operations}):
\begin{align*}
{\color{greenunder}\text{expect to equal }p^{\uparrow F}\bef\text{op}_{P}:}\quad & \gunderline{\text{op}_{M}}\bef p=\text{sop}_{M}\bef\gunderline{\text{ftn}_{M}\bef p}\\
{\color{greenunder}\text{monad morphism composition law of }p:}\quad & =\gunderline{\text{sop}_{M}\bef p^{\uparrow M}}\bef p\bef\text{ftn}_{P}\\
{\color{greenunder}\text{naturality law of }\text{sop}_{M}:}\quad & =p^{\uparrow F}\bef\gunderline{\text{sop}_{M}\bef p}\bef\text{ftn}_{P}=p^{\uparrow F}\bef\gunderline{\text{sop}_{P}\bef\text{ftn}_{P}}=p^{\uparrow F}\bef\text{op}_{P}\quad.
\end{align*}
$\square$

The method of Statement~\ref{subsec:Statement-monatron-lifting-simple-operation}
allows us to lift a \textsf{``}simple\textsf{''} operation from a monad $M$ to any
monad stack $P$ containing $M$, as long as we have a lift function
$p:M\leadsto P$. The lift $p$ will exist if the monad $M$ is at
the deep end of the stack, or if $M$\textsf{'}s transformer supports a base
lift. Accordingly, one must place the continuation monad, the search
monad, the codensity monad, and task-like monads (such as \lstinline!IO!)
at the deep end of the stack, since those monads do not support base
lifts.

The same method allows us to lift a \textsf{``}standard\textsf{''} operation if it
is equivalent to a \textsf{``}simple\textsf{''} operation. The condition for that
equivalence is the compatibility law~(\ref{eq:monatron-standard-operation-compatibility-law}).
If a \textsf{``}standard\textsf{''} operation \lstinline!op! satisfies that law,
the corresponding lifted operation $\text{op}_{P}$ is expressed by
Eq.~(\ref{eq:monatron-lifting-simple-op}).

\paragraph{Lifting \textsf{``}standard\textsf{''} operations}

Some \textsf{``}standard\textsf{''} operations fail the compatibility law~(\ref{eq:monatron-standard-operation-compatibility-law}).
So, they cannot be reduced to a \textsf{``}simple\textsf{''} operation and require
a different method of lifting.

We begin with the task of lifting a \textsf{``}standard\textsf{''} operation $\text{op}:F^{M^{A}}\rightarrow M^{A}$
to a stack $P$ where the monad $M$ is located at the deep end. So,
we assume that $P^{A}=T_{L}^{M,A}$ for some base monad (or stack)
$L$. The lifting of \lstinline!op! to $P$ turns out to be complicated,
so we split the procedure into four steps:
\begin{enumerate}
\item Convert \lstinline!op! into an equivalent \textsf{``}simple\textsf{''} operation
(\lstinline!scop!) in the codensity monad $\text{Cod}^{M,\bullet}$.
\item Lift \lstinline!scop! to the stack $T_{L}^{\text{Cod}^{M,\bullet},A}$
that contains the codensity monad instead of $M$.
\item Transform the stack, replacing the codensity monad $\text{Cod}^{M,\bullet}$
by the original monad $M$.
\item Derive the code for the new operation ($\text{op}_{P}$).
\end{enumerate}
We will now go through these steps in detail.

The first step uses the monad $\text{Cod}^{M,\bullet}$ (the codensity\index{monads!codensity monad}
monad on $M$, see Section~\ref{subsec:The-codensity-monad}). It
turns out that the type of natural transformations $F^{M^{A}}\rightarrow M^{A}$
(the type of \textsf{``}standard\textsf{''} operations in the monad $M$) is \emph{equivalent}
to the type of natural transformations $F^{A}\rightarrow\text{Cod}^{M,A}$
(the type of \textsf{``}simple\textsf{''} operations in the codensity monad on $M$).
To show this, we will prove a more general property that does not
depend on any monads:

\subsubsection{Statement \label{subsec:Statement-monatron-kan-extension-property}\ref{subsec:Statement-monatron-kan-extension-property}}

For any functors $F$, $K$, $L$, the set of natural transformations
of type $\forall A.\,F^{K^{A}}\rightarrow L^{A}$ is isomorphic to
the set of natural transformations of type\footnote{The type $\forall R.\,(A\rightarrow K^{R})\rightarrow L^{R}$ implements
the construction known in category theory as the \textbf{right Kan
extension}\index{right Kan extension} of $L$ along $K$. See \texttt{\href{https://bartoszmilewski.com/2017/04/17/kan-extensions/}{https://bartoszmilewski.com/2017/04/17/kan-extensions/}}}
\[
\forall A.\,F^{A}\rightarrow\forall R.\,(A\rightarrow K^{R})\rightarrow L^{R}\quad,
\]
where naturality laws are required with respect to both $A$ and $R$.

\subparagraph{Proof}

The two directions of the isomorphism are implemented via two functions
\lstinline!inK!, \lstinline!outK!:
\begin{align*}
 & \text{inK}:(\forall B.\,F^{K^{B}}\rightarrow L^{B})\rightarrow F^{A}\rightarrow(A\rightarrow K^{R})\rightarrow L^{R}\quad,\\
 & \quad\quad\text{inK}\,(\text{op}^{:\forall B.\,F^{K^{B}}\rightarrow L^{B}})\triangleq f^{:F^{A}}\rightarrow k^{:A\rightarrow K^{A}}\rightarrow f\triangleright k^{\uparrow F}\triangleright\text{op}^{B=R}\quad,\\
 & \text{outK}:\big(\forall R.\,F^{A}\rightarrow(A\rightarrow K^{R})\rightarrow L^{R}\big)\rightarrow F^{K^{A}}\rightarrow L^{A}\quad,\\
 & \quad\quad\text{outK}\,(\text{cop}^{:F^{A}\rightarrow\forall R.\,(A\rightarrow K^{R})\rightarrow L^{R}})\triangleq g^{:F^{K^{A}}}\rightarrow(g\triangleright\text{cop})^{R=K^{A}}(\text{id}^{K^{A}})\quad.
\end{align*}
We now need to show that \lstinline!inK! and \lstinline!outK! are
inverses of each other. One direction:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{op}:}\quad & \text{op}\triangleright\text{inK}\triangleright\text{outK}=(f\rightarrow k\rightarrow f\triangleright k^{\uparrow F}\triangleright\text{op}\gunderline{)\triangleright\big(}\text{cop}\rightarrow g\rightarrow\text{cop}\,(g)(\text{id})\big)\\
{\color{greenunder}\text{apply function}:}\quad & =g\rightarrow(\gunderline{f\rightarrow k\rightarrow}\,f\triangleright k^{\uparrow F}\triangleright\text{op})\gunderline{(g)(\text{id})}\\
{\color{greenunder}\text{apply function}:}\quad & =g\rightarrow g\triangleright\text{id}^{\uparrow F}\triangleright\text{op}=\gunderline{g\rightarrow g\,\triangleright}\,\text{op}=\text{op}\quad.
\end{align*}

Proving that $\text{outK}\bef\text{inK}=\text{id}$ needs the naturality
law of the \lstinline!cop! functions:
\begin{align*}
 & \text{cop}^{A,R}:F^{A}\rightarrow(A\rightarrow K^{R})\rightarrow L^{R}\quad,\\
 & (f^{:A\rightarrow B})^{\uparrow F}\bef\text{cop}^{B,R}=\text{cop}^{A,R}\bef\big(c^{:(A\rightarrow K^{R})\rightarrow L^{R}}\rightarrow k^{:B\rightarrow K^{R}}\rightarrow(f\bef k)\triangleright c\big)\quad.
\end{align*}
For convenience, we apply both sides of this naturality law to arbitrary
values $x^{:F^{A}}$and $y^{:B\rightarrow K^{R}}$:
\begin{equation}
(x\triangleright f^{\uparrow F}\bef\text{cop})(y)=\text{cop}\,(x\triangleright f^{\uparrow F})(y)\overset{!}{=}\big(x\triangleright\text{cop}\bef(c\rightarrow k\rightarrow(f\bef k)\triangleright c)\big)(y)=\text{cop}\,(x)(f\bef y)\quad.\label{eq:monatron-naturality-law-of-cop}
\end{equation}
We now rewrite $\text{outK}\bef\text{inK}$ to verify the other direction
of the isomorphism:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{cop}:}\quad & \text{cop}\triangleright\text{outK}\triangleright\text{inK}=\big(g\rightarrow\text{cop}\,(g)(\text{id})\big)\triangleright(\text{op}\rightarrow f\rightarrow k\rightarrow f\triangleright k^{\uparrow F}\triangleright\text{op})\\
 & =f\rightarrow k\rightarrow f\triangleright k^{\uparrow F}\triangleright\big(g\rightarrow\text{cop}\,(g)(\text{id})\big)=f\rightarrow k\rightarrow\gunderline{\text{cop}\,(f\triangleright k^{\uparrow F})(\text{id})}\\
{\color{greenunder}\text{naturality law of }\text{cop}:}\quad & =f\rightarrow k\rightarrow\text{cop}(f)(k\bef\text{id})=\gunderline{f\rightarrow k\rightarrow}\,\text{cop}\,(f)(k)=\text{cop}\quad.
\end{align*}

Finally, we need to show that \lstinline!inK! produces \lstinline!cop!
functions that satisfy their naturality law:
\begin{align*}
 & \text{inK}\,(\text{op})(x\triangleright f^{\uparrow F})(y)\overset{?}{=}\text{inK}\,(\text{op})(x)(f\bef y)\quad,\\
 & (f\rightarrow k\rightarrow f\triangleright k^{\uparrow F}\triangleright\text{op})(x\triangleright f^{\uparrow F})(y)\overset{?}{=}(f\rightarrow k\rightarrow f\triangleright k^{\uparrow F}\triangleright\text{op})(x)(f\bef y)\quad,\\
 & x\triangleright f^{\uparrow F}\triangleright y^{\uparrow F}\triangleright\text{op}\overset{?}{=}x\triangleright(f\bef y)^{\uparrow F}\triangleright\text{op}\quad.
\end{align*}
The last line holds due to a property of $\triangleright$-notation:
$x\triangleright f\triangleright g=x\triangleright f\bef g$.

So far, the proof did not require the naturality law of the \lstinline!op!
functions:
\begin{equation}
\text{op}^{A}:F^{K^{A}}\rightarrow L^{A}\quad,\quad\quad(f^{:A\rightarrow B})^{\uparrow K\uparrow F}\bef\text{op}^{B}=\text{op}^{A}\bef f^{\uparrow L}\quad.\label{eq:monatron-naturality-law-of-op}
\end{equation}
 We need to show that any \lstinline!op! function obtained via \lstinline!outK!
will satisfy this naturality law:
\begin{align*}
{\color{greenunder}\text{left-hand side}:}\quad & x^{:F^{K^{A}}}\triangleright f^{\uparrow K\uparrow F}\bef\text{outK}\,(\text{cop})=x\triangleright f^{\uparrow K\uparrow F}\triangleright\big(g\rightarrow\text{cop}\,(g)(\text{id})\big)=\text{cop}\,(x\triangleright f^{\uparrow K\uparrow F})(\text{id})\\
{\color{greenunder}\text{use Eq.~(\ref{eq:monatron-naturality-law-of-cop})}:}\quad & \quad=\text{cop}\,(x)(f^{\uparrow K}\bef\text{id})=\text{cop}\,(x)(f^{\uparrow K})\quad,\\
{\color{greenunder}\text{right-hand side}:}\quad & x\triangleright\text{outK}\,(\text{cop})\triangleright f^{\uparrow L}=x\triangleright\big(g\rightarrow\text{cop}\,(g)(\text{id})\big)\triangleright f^{\uparrow L}=\text{cop}\,(x)(\text{id})\triangleright f^{\uparrow L}\quad.
\end{align*}
The two sides become equal once we require that the function of type
$(A\rightarrow K^{R})\rightarrow L^{R}$ returned by $\text{cop}\,(x)$
be a natural transformation with respect to $R$, with the corresponding
naturality law being 
\[
\text{cop}\,(x)(y\bef f^{\uparrow K})\overset{!}{=}y\triangleright\text{cop}\,(x)\triangleright f^{\uparrow L}=\text{cop}\,(x)(y)\triangleright f^{\uparrow L}\quad.
\]

It remains to show that any \lstinline!cop! function obtained as
\lstinline!inK(op)! will be such that $\text{cop}\,(x)$ is a natural
transformation of type $\forall R.\,(A\rightarrow K^{R})\rightarrow L^{R}$
for any $x^{:F^{A}}$, as long as \lstinline!op! satisfies its naturality
law~(\ref{eq:monatron-naturality-law-of-op}). We rewrite the naturality
law of $\text{cop}\,(x)$:
\begin{align*}
 & \text{cop}\,(x)(y\bef f^{\uparrow K})\overset{?}{=}\text{cop}\,(x)(y)\triangleright f^{\uparrow L}\quad,\text{ or equivalently: }\quad\text{inK}\,(\text{op})(x)(y\bef f^{\uparrow K})\overset{?}{=}\text{inK}\,(\text{op})(x)(y)\triangleright f^{\uparrow L}\quad,\\
 & x\triangleright(y\bef f^{\uparrow K})^{\uparrow F}\triangleright\text{op}\overset{?}{=}x\triangleright y^{\uparrow F}\triangleright\text{op}\triangleright f^{\uparrow L}\quad,\text{ or equivalently: }\quad x\triangleright(y\bef f^{\uparrow K})^{\uparrow F}\bef\text{op}\overset{?}{=}x\triangleright y^{\uparrow F}\bef\text{op}\bef f^{\uparrow L}\quad.
\end{align*}
The last equation holds due to the assumed law~(\ref{eq:monatron-naturality-law-of-op}).
This concludes the proof. $\square$

Using Statement~\ref{subsec:Statement-monatron-kan-extension-property}
with $K=L=M$, we find that a \textsf{``}standard\textsf{''} operation \lstinline!op!
in a monad $M$ is equivalent to a \textsf{``}simple\textsf{''} operation \lstinline!scop!
in the codensity monad $\text{Cod}^{M}$. We define \lstinline!scop!
via \lstinline!op! by
\begin{equation}
\text{scop}:F^{A}\rightarrow(A\rightarrow M^{R})\rightarrow M^{R}\quad,\quad\quad\text{scop}\triangleq f^{:F^{A}}\rightarrow k^{:A\rightarrow M^{R}}\rightarrow f\triangleright k^{\uparrow F}\triangleright\text{op}^{R}\quad.\label{eq:monatron-scop-via-op}
\end{equation}
We can lift \lstinline!scop! to the stack $P^{\prime}\triangleq T_{L}^{\text{Cod}^{M}}$
that contains the codensity monad instead of $M$. The result is a
\textsf{``}simple\textsf{''} operation ($\text{scop}_{P^{\prime}}$) defined by
\[
\text{scop}_{P^{\prime}}:F^{A}\rightarrow T_{L}^{\text{Cod}^{M,\bullet},A}\quad,\quad\quad\text{scop}_{P^{\prime}}\triangleq\text{scop}\bef\text{flift}_{L}^{\text{Cod}^{M}}\quad.
\]
It remains somehow to convert the operation $\text{scop}_{P^{\prime}}$
into a corresponding operation in the stack $P$.

Since the monad $M$ is injectively embedded within $\text{Cod}^{M}$
using the functions \lstinline!inC! and \lstinline!outC! (see Statement~\ref{subsec:Statement-codensity-monad-inC-outC}),
we may use $T_{L}$\textsf{'}s \lstinline!frun! function to transform between
$P$ and $P^{\prime}$ in both directions:
\[
\text{frun}_{L}(\text{inC}):T_{L}^{M}\leadsto T_{L}^{\text{Cod}^{M}}\cong P\leadsto P^{\prime}\quad,\quad\quad\text{frun}_{L}(\text{outC}):T_{L}^{\text{Cod}^{M}}\leadsto T_{L}^{M}\cong P^{\prime}\leadsto P\quad.
\]
One way of converting $\text{scop}_{P^{\prime}}$ into a $P$-operation
would be to compose with $\text{flift}_{L}(\text{outC})$, which creates
a \textsf{``}simple\textsf{''} operation $\text{sop}_{P}$ of type $F^{A}\rightarrow P^{A}$.
However, the resulting operation would not correctly extend \lstinline!op!\textsf{'}s
effect transformation to the stack $P$. To see why, we rewrite $\text{sop}_{P}$
as
\begin{align*}
 & \text{sop}_{P}\triangleq\text{scop}_{P^{\prime}}\bef\text{flift}_{L}(\text{outC})=\text{scop}\bef\gunderline{\text{flift}_{L}\bef\text{frun}_{L}}(\text{outC})\\
{\color{greenunder}\text{monadic naturality law of }\text{flift}_{L}:}\quad & =\text{scop}\bef\text{outC}\bef\text{flift}_{L}=(f\rightarrow k\rightarrow f\triangleright k^{\uparrow F}\triangleright\text{op})\bef\text{outC}\bef\text{flift}_{L}\\
 & =(\gunderline{f\rightarrow f\,\triangleright}\,\text{pu}_{M}^{\uparrow F}\bef\text{op})\bef\text{flift}_{L}=\text{pu}_{M}^{\uparrow F}\bef\text{op}\bef\text{flift}_{L}\quad.
\end{align*}
We find that the operation $\text{sop}_{P}$ is the lifted version
of $\text{sop}\triangleq\text{pu}_{M}^{\uparrow F}\bef\text{op}$,
which would correspond to the \textsf{``}simple\textsf{''} counterpart of \lstinline!op!.
However, by assumption, \lstinline!op! does not satisfy the compatibility
law and is not equivalent to \lstinline!sop!. The operation \lstinline!sop!
does not perform the same transformation of $M$-effects as \lstinline!op!;
so, the operation $\text{sop}_{P}$ fails to be a correct lifting
of \lstinline!op!.

In the derivation, we used the monadic naturality law~(\ref{eq:monadic-naturality-law-of-flift})
of \lstinline!flift! with $\phi\triangleq\text{outC}$, although
\lstinline!outC! is not a monad morphism. This is justified because
certain monad transformers (e.g., the composed-outside transformers)
satisfy the monadic naturality law of \lstinline!flift! even if $\phi$
is not a lawful monad morphism. So, we have shown that $\text{sop}_{P}$
is an incorrect lifting for \emph{some} monad stacks $P$; this is
sufficient for our purposes.

To obtain a correct lifting, the equivalence between \lstinline!op!
and \lstinline!scop! must be expressed differently:

\subsubsection{Statement \label{subsec:Statement-monatron-equivalence-op-cop}\ref{subsec:Statement-monatron-equivalence-op-cop}}

Given a \textsf{``}standard\textsf{''} operation \lstinline!op! in a monad $M$,
define \lstinline!scop! by Eq.~(\ref{eq:monatron-scop-via-op}).
Define the corresponding \textsf{``}standard\textsf{''} operation \lstinline!cop!
(in the codensity monad) via Statement~\ref{subsec:Statement-simple-standard-operations-monatron}:

\begin{wrapfigure}{i}{0.2\columnwidth}%
\begin{centering}
\vspace{-1.1\baselineskip}
\[
\xymatrix{\xyScaleY{1.2pc}\xyScaleX{2.0pc}F^{M^{A}}\ar[d]\sb(0.45){\text{op}}\ar[r]\sb(0.45){\text{inC}^{\uparrow F}} & F^{\text{Cod}^{M,A}}\ar[d]\sp(0.45){\text{cop}}\\
M^{A} & \text{Cod}^{M,A}\ar[l]\sp(0.55){\text{outC}}
}
\]
\par\end{centering}
\vspace{-0.8\baselineskip}
\end{wrapfigure}%

~\vspace{-0.45\baselineskip}
\[
\text{cop}:F^{\text{Cod}^{M,A}}\rightarrow\text{Cod}^{M,A}\quad,\quad\quad\text{cop}\triangleq\text{scop}\bef\text{ftn}_{\text{Cod}}\quad.
\]

Then \lstinline!op! may be expressed through \lstinline!cop! by
the following code:
\begin{equation}
\text{op}=\text{inC}^{\uparrow F}\bef\text{cop}\bef\text{outC}\quad.\label{eq:monatron-op-through-cop}
\end{equation}


\subparagraph{Proof}

In the derivation, we will need the code of $^{\uparrow\text{Cod}}$
and $\text{ftn}_{\text{Cod}}$:
\begin{align*}
 & (f^{:A\rightarrow B})^{\uparrow\text{Cod}}=c^{:\text{Cod}^{M,A}}\rightarrow\forall R.\,k^{:B\rightarrow M^{R}}\rightarrow c(f\bef k)\quad,\\
 & c^{:\text{Cod}^{M,\text{Cod}^{M,A}}}\triangleright\text{ftn}_{\text{Cod}}=k^{:A\rightarrow M^{R}}\rightarrow c\big(d^{:\text{Cod}^{M,A}}\rightarrow d(k)\big)\quad.
\end{align*}

We rewrite the right-hand side of Eq.~(\ref{eq:monatron-op-through-cop})
and use the definitions of \lstinline!cop! and \lstinline!scop!:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{op}:}\quad & \text{inC}^{\uparrow F}\bef\gunderline{\text{cop}}\bef\text{outC}=\gunderline{\text{inC}^{\uparrow F}\bef\text{scop}}\bef\text{ftn}_{\text{Cod}}\bef\text{outC}\\
{\color{greenunder}\text{naturality law of }\text{scop}:}\quad & =\text{scop}\bef\text{inC}^{\uparrow\text{Cod}}\bef\text{ftn}_{\text{Cod}}\bef\text{outC}\\
{\color{greenunder}\text{use Eq.~(\ref{eq:monatron-scop-via-op}) and }^{\uparrow\text{Cod}}:}\quad & =(f\rightarrow k\rightarrow f\triangleright k^{\uparrow F}\triangleright\text{op})\bef(c\rightarrow k\rightarrow c(\text{inC}\bef k))\bef\text{ftn}_{\text{Cod}}\bef\text{outC}\\
{\color{greenunder}\text{compute composition}:}\quad & =f\rightarrow\big(k\rightarrow f\triangleright\gunderline{(\text{inC}\bef k)^{\uparrow F}}\triangleright\text{op}\big)\triangleright\text{ftn}_{\text{Cod}}\triangleright\text{outC}\\
{\color{greenunder}\text{definition of }\text{ftn}_{\text{Cod}}:}\quad & =f\rightarrow\big(k\rightarrow f\triangleright\text{inC}^{\uparrow F}\bef(d\rightarrow d(k))^{\uparrow F}\bef\text{op}\big)\triangleright\text{outC}\\
{\color{greenunder}\text{definition of }\text{outC}:}\quad & =f\rightarrow f\triangleright\text{inC}^{\uparrow F}\bef(\gunderline{d\rightarrow d(\text{pu}_{M})})^{\uparrow F}\bef\text{op}\\
{\color{greenunder}\text{definition of }\text{outC}:}\quad & =f\rightarrow f\triangleright\text{inC}^{\uparrow F}\bef\text{outC}^{\uparrow F}\bef\text{op}=f\rightarrow f\triangleright\text{op}=\text{op}\quad.
\end{align*}
$\square$

We may convert $\text{scop}_{P^{\prime}}$ into the corresponding
\textsf{``}standard\textsf{''} operation ($\text{cop}_{P^{\prime}}$):
\[
\text{cop}_{P^{\prime}}:F^{P^{\prime A}}\rightarrow P^{\prime A}\quad,\quad\text{cop}_{P^{\prime}}\triangleq\text{scop}_{P^{\prime}}\bef\text{ftn}_{P^{\prime}}\quad\quad.
\]
To convert $\text{cop}_{P^{\prime}}$ into $\text{op}_{P}$, we note
that Eq.~(\ref{eq:monatron-op-through-cop}) expresses \lstinline!op!
via \lstinline!cop! using the functions \lstinline!inC! and \lstinline!outC!,
which transform between the monads $M$ and $\text{Cod}^{M}$. Lifting
these functions with $\text{frun}_{L}$, we can express the operation
$\text{op}_{P}$ via $\text{cop}_{P^{\prime}}$ as follows:%
\begin{comment}
precarious formatting
\end{comment}

\begin{wrapfigure}{i}{0.24\columnwidth}%
\begin{centering}
\vspace{-2.6\baselineskip}
\[
\xymatrix{\xyScaleY{1.2pc}\xyScaleX{3.0pc}F^{P^{A}}\ar[d]\sb(0.45){\text{op}_{P}}\ar[r]\sb(0.45){(\text{frun}_{L}(\text{inC}))^{\uparrow F}} & F^{P^{\prime A}}\ar[d]\sp(0.45){\text{cop}_{P^{\prime}}}\\
P^{A} & P^{\prime A}\ar[l]\sp(0.55){\text{frun}_{L}(\text{outC})}
}
\]
\par\end{centering}
\vspace{0.2\baselineskip}
\end{wrapfigure}%

~\vspace{-0.45\baselineskip}
\begin{equation}
\text{op}_{P}=(\text{frun}_{L}(\text{inC}))^{\uparrow F}\bef\text{cop}_{P^{\prime}}\bef\text{frun}_{L}(\text{outC})\quad.\label{eq:monatron-op-P-via-cop}
\end{equation}

The following statement shows that the resulting operation ($\text{op}_{P}$)
is a correct lifting of \lstinline!op!.

\subsubsection{Statement \label{subsec:Statement-monatron-standard-lifting-op}\ref{subsec:Statement-monatron-standard-lifting-op}}

The function $\text{op}_{P}$ defined by Eq.~(\ref{eq:monatron-op-P-via-cop})
is a monadically natural lifting of \lstinline!op! if the monad transformer
$T_{L}$ has a \lstinline!frun! method and if the monadic naturality
law of \lstinline!flift! holds for \lstinline!outC! (even though
\lstinline!outC! is not a monad morphism).\footnote{This version of the monadic naturality law holds for all monad transformers
that support \lstinline!frun!.}

\subparagraph{Proof}

The lifting of $M$ to $P$ is given by $\text{flift}_{L}$. To verify
the monadic naturality law of $\text{op}_{P}$, we will need to use
the monad morphism composition law of $\text{flift}_{L}$:
\[
\text{flift}_{L}^{\uparrow\text{Cod}}\bef\text{flift}_{L}\bef\text{ftn}_{P^{\prime}}=\text{ftn}_{\text{Cod}}\bef\text{flift}_{L}\quad.
\]
So, we will use various laws to move the two functions $\text{flift}_{L}$
towards $\text{ftn}_{P^{\prime}}$. We write:
\begin{align*}
{\color{greenunder}\text{expect to equal }(\text{op}\bef\text{flift}_{L}):}\quad & \text{flift}_{L}^{\uparrow F}\bef\text{op}_{P}=\text{flift}_{L}^{\uparrow F}\bef(\text{frun}_{L}(\text{inC}))^{\uparrow F}\bef\text{cop}_{P^{\prime}}\bef\text{frun}_{L}(\text{outC})\\
 & =\big(\gunderline{\text{flift}_{L}\bef\text{frun}_{L}(\text{inC})}\big)^{\uparrow F}\bef\text{scop}_{P^{\prime}}\bef\text{ftn}_{P^{\prime}}\bef\text{frun}_{L}(\text{outC})\\
{\color{greenunder}\text{monadic naturality law of }\text{flift}_{L}:}\quad & =\big(\text{inC}\bef\text{flift}_{L}\gunderline{\big)^{\uparrow F}\bef\text{scop}}\bef\text{flift}_{L}\bef\text{ftn}_{P^{\prime}}\bef\text{frun}_{L}(\text{outC})\\
{\color{greenunder}\text{naturality law of }\text{scop}:}\quad & =\text{scop}\bef\text{inC}^{\uparrow\text{Cod}}\bef\gunderline{\text{flift}_{L}^{\uparrow\text{Cod}}\bef\text{flift}_{L}\bef\text{ftn}_{P^{\prime}}}\bef\text{frun}_{L}(\text{outC})\\
{\color{greenunder}\text{composition law of }\text{flift}_{L}:}\quad & =\text{scop}\bef\text{inC}^{\uparrow\text{Cod}}\bef\text{ftn}_{\text{Cod}}\bef\gunderline{\text{flift}_{L}\bef\text{frun}_{L}(\text{outC})}\\
{\color{greenunder}\text{monadic naturality law of }\text{flift}_{L}:}\quad & =\text{scop}\bef\text{inC}^{\uparrow\text{Cod}}\bef\text{ftn}_{\text{Cod}}\bef\text{outC}\bef\text{flift}_{L}\quad.
\end{align*}
In the last line, we used the monadic naturality law of $\text{flift}_{L}$
applied to \lstinline!outC!, which holds by assumption. We now reuse
the last derivation in the proof of Statement~\ref{subsec:Statement-monatron-equivalence-op-cop},
where we found that
\[
\text{scop}\bef\text{inC}^{\uparrow\text{Cod}}\bef\text{ftn}_{\text{Cod}}\bef\text{outC}=\text{op}\quad.
\]
This completes the proof of the equation $\text{flift}_{L}^{\uparrow F}\bef\text{op}_{P}=\text{op}\bef\text{flift}_{L}$.
$\square$

\paragraph{Lifting to the base monad}

The method just shown lifts \textsf{``}standard\textsf{''} $M$-operations to monad
stacks $L\varangle M$ where the monad $M$ is located at the deep
end. If $M$ is located somewhere else in the stack, there exist monads
$L$ and $N$ such that the stack $P$ is expressed as $P=L\varangle M\varangle N$.
If we knew how to lift $M$-operations to the stack $M\varangle N$
(where $M$ is the base monad), we will then be able to lift them
also to $P$ since the monad $M\varangle N$ is located at the deep
end of $P$. So, it remains to see how $M$-operations may be lifted
to a stack $M\varangle N$ that has $M$ as its base monad.

All \textsf{``}standard\textsf{''} $M$-operations that satisfy the compatibility
law~(\ref{eq:monatron-standard-operation-compatibility-law}) are
equivalent to \textsf{``}simple\textsf{''} operations and are lifted to the stack
$Q\triangleq M\varangle N$ using its \lstinline!blift! function.
(As before, we require that the monad $M$\textsf{'}s transformer should support
base lifts.) It remains to consider \textsf{``}standard\textsf{''} operations $\text{op}:F\circ M\leadsto M$
that do \emph{not} satisfy the compatibility law. Our goal is to obtain
a lifted operation $\text{op}_{Q}:F\circ Q\leadsto Q$ out of a given
non-\textsf{``}simple\textsf{''} operation \lstinline!op!.

If $M$\textsf{'}s transformer is composed-inside (so that $Q^{A}\triangleq M^{N^{A}}$),
defining $\text{op}_{Q}$ is straightforward:
\[
\text{op}_{Q}:F^{M^{N^{A}}}\rightarrow M^{N^{A}}\quad,\quad\quad\text{op}_{Q}\triangleq\text{op}^{N^{A}}\quad.
\]
To show that $\text{op}_{Q}$ is a monadically natural lifting of
\lstinline!op!, compute:
\begin{align*}
{\color{greenunder}\text{expect to equal }(\text{op}\bef\text{blift}_{M}):}\quad & \text{blift}_{M}^{\uparrow F}\bef\text{op}_{Q}=\text{pu}_{N}^{\uparrow M\uparrow F}\bef\text{op}_{Q}\\
{\color{greenunder}\text{naturality law of }\text{op}_{Q}:}\quad & =\text{op}_{Q}\bef\text{pu}_{N}^{\uparrow M}=\text{op}\bef\text{blift}_{M}\quad.
\end{align*}

This case covers rigid monads (such as \lstinline!Reader! with its
non-\textsf{``}simple\textsf{''} \lstinline!local! operation) but does not apply,
e.g., to the \lstinline!Writer! monad\textsf{'}s \lstinline!clear! operation
or to other non-rigid monads. The \lstinline!Writer! monad\textsf{'}s transformer
is composed-outside, so $M\varangle N=N\circ M$. We could implement
a function of type $F^{N^{M^{A}}}\rightarrow N^{M^{A}}$given a function
$\text{op}:F^{M^{A}}\rightarrow M^{A}$, but that function will not
be a monadically natural lifting of \lstinline!op!:

\subsubsection{Statement \label{subsec:Statement-monatron-not-natural-lifting-linear-monads}\ref{subsec:Statement-monatron-not-natural-lifting-linear-monads}}

Assume that $M$ is a monad with a composed-outside transformer, $N$
is another monad, and $\text{op}:F^{M^{A}}\rightarrow M^{A}$ is a
given $M$-operation that does not satisfy the compatibility law~(\ref{eq:monatron-standard-operation-compatibility-law}).
Then the function $\text{op}_{Q}$ defined by
\[
\text{op}_{Q}:F^{N^{M^{A}}}\rightarrow N^{M^{A}}\quad,\quad\quad\text{op}_{Q}\triangleq\text{pu}_{M}^{\uparrow F}\bef\text{op}\bef\text{pu}_{N}\bef\text{ftn}_{N\circ M}
\]
is \emph{not} a monadically natural lifting of \lstinline!op! to
the stack $Q\triangleq M\varangle N\cong N\circ M$.

\subparagraph{Proof}

Using the definition $\text{blift}_{M}\triangleq\text{pu}_{N}$, we
write the two sides of the monadic naturality law:
\begin{align*}
{\color{greenunder}\text{left-hand side}:}\quad & \text{op}\bef\text{blift}_{M}=\text{op}\bef\text{pu}_{N}\quad,\\
{\color{greenunder}\text{right-hand side}:}\quad & \text{blift}_{M}^{\uparrow F}\bef\text{op}_{Q}=\gunderline{\text{pu}_{N}^{\uparrow F}\bef\text{pu}_{M}^{\uparrow F}}\bef\text{op}\bef\text{pu}_{N}\bef\text{ftn}_{N\circ M}\\
{\color{greenunder}\text{naturality law of }\text{pu}_{M}:}\quad & =\text{pu}_{M}^{\uparrow F}\bef\gunderline{\text{pu}_{N}^{\uparrow M\uparrow F}\bef\text{op}}\bef\text{pu}_{N}\bef\text{ftn}_{N\circ M}\\
{\color{greenunder}\text{naturality law of }\text{op}:}\quad & \quad=\text{pu}_{M}^{\uparrow F}\bef\text{op}\bef\gunderline{\text{pu}_{N}^{\uparrow M}\bef\text{pu}_{N}}\bef\text{ftn}_{N\circ M}=\text{pu}_{M}^{\uparrow F}\bef\text{op}\bef\gunderline{\text{blift}_{M}^{\uparrow M}\bef\text{blift}_{M}\bef\text{ftn}_{N\circ M}}\\
{\color{greenunder}\text{composition law of }\text{blift}:}\quad & \quad=\text{pu}_{M}^{\uparrow F}\bef\text{op}\bef\text{ftn}_{M}\bef\gunderline{\text{blift}_{M}}=\text{pu}_{M}^{\uparrow F}\bef\text{op}\bef\text{ftn}_{M}\bef\text{pu}_{N}\quad.
\end{align*}
The two sides would be equal if
\[
\text{op}\bef\text{pu}_{N}\overset{?}{=}\text{pu}_{M}^{\uparrow F}\bef\text{op}\bef\text{ftn}_{M}\bef\text{pu}_{N}\quad.
\]
This would be true if \lstinline!op! satisfied the compatibility
law~(\ref{eq:monatron-standard-operation-compatibility-law}), because
then we would have
\[
\text{pu}_{M}^{\uparrow F}\bef\text{op}\bef\text{ftn}_{M}=\gunderline{\text{pu}_{M}^{\uparrow F}\bef\text{ftn}_{M}^{\uparrow F}}\bef\text{op}=\text{op}\quad.
\]
However, by assumption the law~(\ref{eq:monatron-standard-operation-compatibility-law})
does not hold for \lstinline!op!. To see that this is sufficient
to destroy the monadic naturality of $\text{op}_{Q}$, choose $F\triangleq\text{Id}$,
$N\triangleq\text{Id}$, $M^{A}\triangleq A\times W$ (a \lstinline!Writer!
monad), and \lstinline!op!$=$\lstinline!clear!:
\[
\text{clear}:M^{A}\rightarrow M^{A}\quad,\quad\quad\text{clear}\triangleq a^{:A}\times\_^{:W}\rightarrow a\times e_{W}\quad.
\]
Then $\text{pu}_{N}=\text{id}$, and we compute $\text{pu}_{M}^{\uparrow F}\bef\text{clear}\bef\text{ftn}_{M}\bef\text{pu}_{N}$
as a function of type $A\times W\rightarrow A\times W$:
\begin{align*}
 & \text{pu}_{M}^{\uparrow F}\bef\text{clear}\bef\text{ftn}_{M}\bef\text{pu}_{N}=(a\times w\rightarrow a\times w\times e_{W})\bef(b^{:A\times W}\times\_^{:W}\rightarrow b\times e_{W})\bef\text{ftn}_{M}\\
 & =a\times w\rightarrow\text{ftn}_{M}(a\times w\times e_{W})=a\times w\rightarrow a\times w=\text{id}\quad.
\end{align*}
This is not equal to \lstinline!clear! because \lstinline!clear!
is not an identity function. $\square$

As the case of the \lstinline!Writer! monad shows, it does not seem
possible to implement a monadically natural lifting to the base monad
for all monads $M$ at once. The method of Statements~\ref{subsec:Statement-monatron-equivalence-op-cop}\textendash \ref{subsec:Statement-monatron-standard-lifting-op}
cannot be used because the codensity monad whose transformer does
not support base lifts. So, lifting those operations requires custom
code adapted to the particular structure of the functor $F$ and the
base monad $M$. For example, we may lift the \lstinline!Writer!
monad\textsf{'}s \lstinline!clear! operation to any stack $Q\triangleq M\varangle N\cong N\circ M$
as follows:

\subsubsection{Statement \label{subsec:Statement-monatron-lifting-writer-clear-to-base}\ref{subsec:Statement-monatron-lifting-writer-clear-to-base}}

For any monad $N$, define $Q\triangleq\text{Writer}^{W,\bullet}\varangle N$,
so $Q^{A}\triangleq N^{A\times W}$. A monadically natural lifting
of the \lstinline!Writer! monad\textsf{'}s \lstinline!clear! operation to
$Q$ is then defined by
\[
\text{clear}_{Q}:N^{A\times W}\rightarrow N^{A\times W}\quad,\quad\quad\text{clear}_{Q}\triangleq\text{clear}^{\uparrow N}\quad.
\]


\subparagraph{Proof}

To verify the monadic naturality law using $\text{blift}_{\text{Writer}}\triangleq\text{pu}_{N}$
and $F=\text{Id}$:
\begin{align*}
{\color{greenunder}\text{expect to equal }(\text{clear}\bef\text{pu}_{N}):}\quad & \text{pu}_{N}^{\uparrow F}\bef\text{clear}_{Q}=\text{pu}_{N}\bef\text{clear}^{\uparrow N}\\
{\color{greenunder}\text{naturality law of }\text{pu}_{N}:}\quad & =\text{clear}\bef\text{pu}_{N}\quad.
\end{align*}
$\square$

A similar case is the \lstinline!Either! monad\textsf{'}s \lstinline!handle!
operation:
\[
\text{handle}:\left(E\rightarrow E+A\right)\times\left(E+A\right)\rightarrow E+A\quad,\quad\quad\text{handle}\triangleq h^{:E\rightarrow E+A}\times m^{:E+A}\rightarrow m\triangleright\,\begin{array}{|c||c|}
 & E+A\\
\hline E & h\\
A & a\rightarrow\bbnum 0+a
\end{array}\quad.
\]
This operation is of the \textsf{``}standard\textsf{''} form with the functor $F^{B}\triangleq\left(E\rightarrow B\right)\times B$
but is not equivalent to a \textsf{``}simple\textsf{''} operation. Custom code is
needed to lift the handle operation to a stack $Q\triangleq\text{Either}^{E,\bullet}\varangle N$:

\subsubsection{Statement \label{subsec:Statement-monatron-lifting-either-handle-to-base}\ref{subsec:Statement-monatron-lifting-either-handle-to-base}}

For any monad $N$, define $Q\triangleq\text{Either}^{E,\bullet}\varangle N$,
so $Q^{A}\triangleq N^{E+A}$ and $\text{pu}_{Q}(a)=\text{pu}_{N}(\bbnum 0+a)$.
Then a monadically natural lifting of the \lstinline!Either! monad\textsf{'}s
\lstinline!handle! operation to $Q$ is:
\[
\text{handle}_{Q}:(E\rightarrow Q^{A})\times Q^{A}\rightarrow Q^{A}\quad,\quad\quad\text{handle}_{Q}\triangleq h^{:E\rightarrow N^{E+A}}\times n^{:N^{E+A}}\rightarrow n\triangleright\text{flm}_{N}\bigg(\,\begin{array}{|c||c|}
 & N^{E+A}\\
\hline E & h\\
A & \text{pu}_{Q}
\end{array}\,\bigg)\quad.
\]


\subparagraph{Proof}

To verify the monadic naturality law using $\text{blift}_{\text{Either}}\triangleq\text{pu}_{N}$
and $F^{B}\triangleq\left(E\rightarrow B\right)\times B$:
\begin{align*}
{\color{greenunder}\text{expect }(\text{handle}\bef\text{pu}_{N}):}\quad & \text{pu}_{N}^{\uparrow F}\bef\text{handle}_{Q}=\big(h^{:E\rightarrow E+A}\times m^{:E+A}\rightarrow(h\bef\text{pu}_{N})\times(m\triangleright\text{pu}_{N})\big)\bef\text{handle}_{Q}\\
 & =h\times m\rightarrow m\triangleright\gunderline{\text{pu}_{N}\triangleright\text{flm}_{N}}\bigg(\,\begin{array}{|c||c|}
 & N^{E+A}\\
\hline E & h\bef\text{pu}_{N}\\
A & \text{pu}_{Q}
\end{array}\,\bigg)=h\times m\rightarrow m\triangleright\,\begin{array}{|c||c|}
 & N^{E+A}\\
\hline E & h\bef\text{pu}_{N}\\
A & \text{pu}_{Q}
\end{array}\\
 & =h\times m\rightarrow m\triangleright\,\begin{array}{|c||c|}
 & N^{E+A}\\
\hline E & h\\
A & a\rightarrow\bbnum 0+a
\end{array}\,\bef\text{pu}_{N}=\text{handle}\bef\text{pu}_{N}\quad.
\end{align*}
$\square$

After writing custom code for lifting each \textsf{``}standard\textsf{''} but non-\textsf{``}simple\textsf{''}
operation to the base monad of a stack, we will be able to lift those
operations to arbitrary monad stacks. The length of the required custom
code is linear in the number of such operations.

\paragraph{\textsf{``}Flipped-standard\textsf{''} operations}

It remains to lift operations that have neither a \textsf{``}fixed-type\textsf{''},
nor \textsf{``}simple\textsf{''}, nor a \textsf{``}standard\textsf{''} type signature. Four such operations
are shown in Table~\ref{tab:effectful-operations-for-some-monads},
namely \lstinline!filter!, \lstinline!collect!, \lstinline!process!,
and \lstinline!callcc!. As we know from Chapter~\ref{chap:Filterable-functors},
the \lstinline!filter! function is equivalent to \lstinline!deflate!
with type signature $\text{List}^{\bbnum 1+A}\rightarrow\text{List}^{A}$.
Then the type signatures of \lstinline!deflate! and \lstinline!process!
are of the \textsf{``}\textbf{flipped-standard}\textsf{''} form $M^{F^{A}}\rightarrow M^{A}$,
where $F$ is some functor. The \lstinline!collect! operation can
be also transformed to a \textsf{``}flipped-standard\textsf{''} form:

\subsubsection{Statement \label{subsec:Statement-monatron-collect-operation}\ref{subsec:Statement-monatron-collect-operation}}

The type of \lstinline!Writer! monad\textsf{'}s \lstinline!collect! operation,
\[
\text{collect}:\forall A.\,A\times W\rightarrow(A\times W)\times W\quad,
\]
 is equivalent to the type $\forall A.\,(W\rightarrow A)\times W\rightarrow A\times W$. 

\subparagraph{Proof}

We use Statement~\ref{subsec:Statement-monatron-kan-extension-property}
with the functors $F$, $K$, $L$ defined as $F^{A}\triangleq A\times W$,
$K^{A}\triangleq W\rightarrow A$, and $L^{A}\triangleq A\times W$.
The result is the type equivalence between
\[
\forall A.\,F^{K^{A}}\rightarrow L^{A}=\forall A.\,\left(W\rightarrow A\right)\times W\rightarrow A\times W
\]
and
\[
\forall A.\,F^{A}\rightarrow\forall R.\,(A\rightarrow K^{R})\rightarrow L^{R}=\forall A.\,A\times W\rightarrow\forall R.\,(A\rightarrow W\rightarrow R)\rightarrow R\times W\quad.
\]
Transforming the last type via the covariant Yoneda identity, we obtain
the type of \lstinline!collect!:
\begin{align*}
 & \forall A.\,A\times W\rightarrow\forall R.\,(\gunderline{A\rightarrow W\rightarrow}\,R)\rightarrow R\times W\cong\forall A.\,A\times W\rightarrow\gunderline{\forall R.\,}(A\times W\rightarrow\gunderline{R)\rightarrow R}\times W\\
 & \cong\forall A.\,A\times W\rightarrow\left(A\times W\right)\times W\quad.
\end{align*}
$\square$

It follows that \lstinline!collect! may be expressed equivalently
through the operation that we will denote by \lstinline!coll!, with
type $\text{Writer}^{W,W\rightarrow A}\rightarrow\text{Writer}^{W,A}$.
That type is of \textsf{``}flipped-standard\textsf{''} form, $M^{F^{A}}\rightarrow M^{A}$,
where $M^{A}=\text{Writer}^{W,A}$ and $F^{A}\triangleq W\rightarrow A$.

If an operation of \textsf{``}flipped-standard\textsf{''} form ($M^{F^{A}}\rightarrow M^{A}$)
satisfies a suitable compatibility law, it is equivalent to a \textsf{``}simple\textsf{''}
operation ($F^{A}\rightarrow M^{A}$):

\subsubsection{Statement \label{subsec:Statement-monatron-flipped-standard-op-equivalent-to-sop}\ref{subsec:Statement-monatron-flipped-standard-op-equivalent-to-sop}}

The set of functions of type $M^{F^{A}}\rightarrow M^{A}$ that obey
the compatibility law

\begin{wrapfigure}{i}{0.25\columnwidth}%
\begin{centering}
\vspace{-2.3\baselineskip}
\[
\xymatrix{\xyScaleY{1.2pc}\xyScaleX{2.5pc}M^{M^{F^{A}}}\ar[d]\sb(0.45){\text{ftn}_{M}}\ar[r]\sb(0.55){\text{op}^{\uparrow M}} & M^{M^{A}}\ar[d]\sp(0.45){\text{ftn}_{M}}\\
M^{P^{A}}\ar[r]\sp(0.5){\text{op}} & M^{A}
}
\]
\par\end{centering}
\vspace{-0.2\baselineskip}
\end{wrapfigure}%

~\vspace{-0.45\baselineskip}
\[
\text{op}^{\uparrow M}\bef\text{ftn}_{M}=\text{ftn}_{M}\bef\text{op}
\]
is isomorphic to the set of functions of type $F^{A}\rightarrow M^{A}$.
(Here we assume that $M$ is a monad and $F$ is a functor.)

\subparagraph{Proof}

Given a function $\text{op}:M^{F^{A}}\rightarrow M^{A}$, define the
corresponding operation $\text{sop}:F^{A}\rightarrow M^{A}$ as
\[
\text{sop}\triangleq\text{pu}_{M}\bef\text{op}\quad.
\]
Given a function $\text{sop}:F^{A}\rightarrow M^{A}$, define the
corresponding operation 
\[
\text{op}\triangleq\text{sop}^{\uparrow M}\bef\text{ftn}_{M}=\text{flm}_{M}(\text{sop})\quad.
\]

To verify one direction of the isomorphism, substitute \lstinline!sop!
into \lstinline!op!:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{op}:}\quad & \text{sop}^{\uparrow M}\bef\text{ftn}_{M}=(\text{pu}_{M}\bef\gunderline{\text{op})^{\uparrow M}\bef\text{ftn}_{M}}\\
{\color{greenunder}\text{compatibility law of }\text{op}:}\quad & =\gunderline{\text{pu}_{M}^{\uparrow M}\bef\text{ftn}_{M}}\bef\text{op}=\text{op}\quad.
\end{align*}

To verify the reverse direction of the isomorphism, substitute \lstinline!op!
into \lstinline!sop!:
\begin{align*}
{\color{greenunder}\text{expect to equal }\text{sop}:}\quad & \text{pu}_{M}\bef\text{op}=\text{pu}_{M}\bef\text{sop}^{\uparrow M}\bef\text{ftn}_{M}\\
{\color{greenunder}\text{naturality law of }\text{pu}_{M}:}\quad & =\text{sop}\bef\gunderline{\text{pu}_{M}\bef\text{ftn}_{M}}=\text{sop}\quad.
\end{align*}

If an operation \lstinline!op! is defined via \lstinline!sop!, the
compatibility law of \lstinline!op! will hold automatically:
\begin{align*}
{\color{greenunder}\text{expect to equal }(\text{ftn}_{M}\bef\text{op}):}\quad & \text{op}^{\uparrow M}\bef\text{ftn}_{M}=(\text{sop}^{\uparrow M}\bef\gunderline{\text{ftn}_{M})^{\uparrow M}\bef\text{ftn}_{M}}\\
{\color{greenunder}\text{associativity law of }\text{ftn}_{M}:}\quad & =\gunderline{\text{sop}^{\uparrow M\uparrow M}\bef\text{ftn}_{M}}\bef\text{ftn}_{M}=\text{ftn}_{M}\bef\text{sop}^{\uparrow M}\bef\text{ftn}_{M}=\text{ftn}_{M}\bef\text{op}\quad.
\end{align*}
$\square$

The \textsf{``}flipped-standard\textsf{''} operations that are equivalent to \textsf{``}simple\textsf{''}
operations may be lifted to monad stacks similarly to the \textsf{``}standard\textsf{''}
operations that are equivalent to \textsf{``}simple\textsf{''} operations. An example
of such an operation is \lstinline!deflate!: if the monad $M$ is
at the same time a filterable functor, it is reasonable to require
the \index{compatibility law!of deflate@of \texttt{deflate}}compatibility
law:
\[
\text{deflate}^{\uparrow M}\bef\text{ftn}_{M}=\text{ftn}_{M}\bef\text{deflate}\quad.
\]
This law holds for the \lstinline!List! monad (filtering before flattening
or after flattening gives the same results). One can show that \lstinline!deflate!
is equivalent to a \textsf{``}simple\textsf{''} operation that we will call \lstinline!defl!:
\[
\text{defl}:\bbnum 1+A\rightarrow\text{List}^{A}\quad,\quad\quad\text{defl}\triangleq\,\begin{array}{|c||cc|}
 & \bbnum 1 & A\times\text{List}^{A}\\
\hline \bbnum 1 & \text{id} & \bbnum 0\\
A & \bbnum 0 & a\rightarrow a\times(\bbnum 1+\bbnum 0)
\end{array}\quad,\quad\quad\text{deflate}=\text{flm}_{\text{List}}(\text{defl})\quad.
\]

However, the other two operations of \textsf{``}flipped-standard\textsf{''} signature
(\lstinline!collect! and \lstinline!process!) are \emph{not} equivalent
to \textsf{``}simple\textsf{''} operations. Let us see whether those operations can
be lifted in a uniform way.

{*}{*}{*}cannot be base-lifted unless they are equivalent to \textsf{``}simple\textsf{''}
operations $F^{A}\rightarrow M^{A}$. Can be foreign-lifted.

Co-product to represent a product of operations as a co-product of
functors $F$ (but this doesn't work for flipped standard operations)

Simple operations lifted via the codensity monad give the same lifted
operations as when lifted directly

Any monad has $M^{M^{A}}\rightarrow M^{A}$, so $F=M$, and it is
a \textsf{``}simple\textsf{''} operation with identity function $M\leadsto M$

A free monad on $F$ has simple operation $F\leadsto M$. Free monads
cannot represent non-simple, standard or flipped-standard operations.

\subsection{Exercises\index{exercises}}

\subsubsection{Exercise \label{subsec:Exercise-monad-stack-1}\ref{subsec:Exercise-monad-stack-1}}

Define type constructors for the given monad stacks and for their
transformers:

\textbf{(a)} \lstinline!List!$\varangle$\lstinline!Eval!

\textbf{(b)} \lstinline!Try!$\varangle$\lstinline!Writer[W, *]!

\textbf{(c)} \lstinline!Cont[R, *]!$\varangle$\lstinline!Try!$\varangle$\lstinline!State[S, *]!

\subsubsection{Exercise \label{subsec:Exercise-monad-stack-1-1}\ref{subsec:Exercise-monad-stack-1-1}}

Consider a monad stack $P\triangleq K_{1}\varangle...\varangle K_{n}$
where each of the monads $K_{i}$ (for $i=1,...,n$) has a runner
$\theta_{i}:K_{i}^{A}\rightarrow A$. Assume that the monads $K_{i}$
have complete monad transformers, so that all base runners are defined.
Show that each runner $\theta_{i}$ can be lifted to the stack $P$,
giving a monad morphism $\bar{\theta}_{i}$ with type signature
\[
\bar{\theta}_{i}:K_{1}\varangle...\varangle K_{n}\leadsto K_{1}\varangle...\varangle K_{i-1}\varangle K_{i+1}\varangle...\varangle K_{n}\quad.
\]
Prove that all runners $\bar{\theta}_{i}$ commute: $\bar{\theta}_{i}\bef\bar{\theta}_{j}=\bar{\theta}_{j}\bef\bar{\theta}_{i}$
for all $i$ and $j$ between $1$ and $n$.

\subsubsection{Exercise \label{subsec:Exercise-monad-transformer-extra-layer-4}\ref{subsec:Exercise-monad-transformer-extra-layer-4} }

Statement~\ref{subsec:Statement-M-to-M-times-M-is-monadic-morphism}
shows that the duplicating function $\Delta:M\leadsto M\times M$
is a monad morphism for an arbitrary monad $M$. Prove that the same
holds for all similarly defined functions $M\leadsto M\times M\times M$,
$M\leadsto M\times M\times M\times M$, and so on.

\subsubsection{Exercise \label{subsec:Exercise-monad-transformer-extra-layer}\ref{subsec:Exercise-monad-transformer-extra-layer} }

We know from Statement~\ref{subsec:Statement-pure-M-is-monad-morphism}
that $\text{pu}_{M}$ is a monad morphism from the identity monad
($\text{Id}$) to a given monad $M$. Show that there are no other
such monad morphisms $\phi$:
\[
\phi:\text{Id}\leadsto M\quad,\quad\text{or equivalently,}\quad\quad\phi^{A}:A\rightarrow M^{A}\quad.
\]
In other words, prove that any such monad morphism $\phi$ must be
equal to $M$\textsf{'}s \lstinline!pure! method: $\phi=\text{pu}_{M}$. (This
shows that the identity monad is an initial object in the category
of monads.)%
\begin{comment}
Solution:

The identity law of monad morphisms is
\[
\text{pu}_{\text{Id}}\bef\phi=\text{pu}_{M}\quad.
\]
Since $\text{pu}_{\text{Id}}=\text{id}$, we obtain $\phi=\text{pu}_{M}$.
There can be no other monad morphisms $\text{Id}\leadsto M$.
\end{comment}


\subsubsection{Exercise \label{subsec:Exercise-monad-transformer-extra-layer-5}\ref{subsec:Exercise-monad-transformer-extra-layer-5}}

\textbf{(a)} Show that for any monad $M$, there is only one monad
morphism $\varepsilon:M\leadsto\bbnum 1$, where $\bbnum 1$ denotes
the unit monad, $L^{A}=\bbnum 1$. (This shows that the unit monad
is a terminal object in the category of monads.)

\textbf{(b)} Show that a monad morphism $\phi:\bbnum 1\leadsto M$
between the unit monad and some monad $M$ is possible only if $M$
is a unit monad ($M^{A}\triangleq\bbnum 1$).

\subsubsection{Exercise \label{subsec:Exercise-monad-transformer-extra-layer-3}\ref{subsec:Exercise-monad-transformer-extra-layer-3}}

For any given monad $M$, consider a function $\text{dbl}:M^{A}\rightarrow M^{A}$
defined as

\begin{wrapfigure}{l}{0.52\columnwidth}%
\vspace{-0.5\baselineskip}
\begin{lstlisting}
def double[M[_]: Monad, A](m: M[A]): M[A] = for {
  _ <- m
  x <- m
} yield x
\end{lstlisting}

\vspace{-1.5\baselineskip}
\end{wrapfigure}%

~\vspace{-0.4\baselineskip}
\begin{align*}
m^{:M^{A}}\triangleright\text{dbl} & \triangleq m\triangleright\text{flm}_{M}(\_^{:A}\rightarrow m)\\
 & =m\triangleright(\_\rightarrow m)^{\uparrow M}\bef\text{ftn}_{M}\quad.
\end{align*}

Heuristically, this function \textsf{``}doubles\textsf{''} the $M$-effect in a given
monadic value $m$ while keeping the value $x^{:A}$, for an arbitrary
monad $M$. 

\textbf{(a)} Show that the function \lstinline!double[M, A]! is a
\emph{monadically natural} transformation $M^{A}\rightarrow M^{A}$
with respect to the monad type parameter $M$. The monadic naturality
law requires, for any two monads $M$, $N$ and any monad morphism
$\phi^{:M\leadsto N}$, the following equation:
\[
\text{dbl}^{M}\bef\phi=\phi\bef\text{dbl}^{N}\quad.
\]

\textbf{(b)} Show that (at least for some monads $M$) the function
\lstinline!double! is \emph{not} a monad morphism $M\leadsto M$. 

\subsubsection{Exercise \label{subsec:Exercise-monad-morphism-reader-state}\ref{subsec:Exercise-monad-morphism-reader-state}}

Consider the monads $\text{Reader}^{R,A}$ and $\text{State}^{R,A}$
(with the same fixed type $R$). 

\textbf{(a)} Implement a monad morphism $\text{Reader}^{R,A}\rightarrow\text{State}^{R,A}$
and prove that its laws hold.

\textbf{(b)} Show that a function of type $\text{State}^{R,A}\rightarrow\text{Reader}^{R,A}$
\emph{cannot} be a monad morphism.

\subsubsection{Exercise \label{subsec:Exercise-monad-morphism-writer-state}\ref{subsec:Exercise-monad-morphism-writer-state}}

Consider the monads $\text{Writer}^{W,A}$ and $\text{State}^{W,A}$
(with a fixed monoid type $W$). 

\textbf{(a)} Implement a monad morphism $\text{Writer}^{W,A}\rightarrow\text{State}^{W,A}$
and prove that its laws hold.

\textbf{(b)} Show that a function of type $\text{State}^{W,A}\rightarrow\text{Writer}^{W,A}$
\emph{cannot} be a monad morphism.

\subsubsection{Exercise \label{subsec:Exercise-monad-transformer-extra-layer-2}\ref{subsec:Exercise-monad-transformer-extra-layer-2} }

Suppose $T_{L}$ is a lawful monad transformer for a base monad $L$
and a foreign monad $M$. Can we modify $T_{L}$ and construct another
monad transformer for $L$ that still satisfies all transformer laws?

One possibility is to compose $T_{L}^{M,A}$ with an extra layer of
the monads $L$ or $M$. Define $U$ and $V$ by
\[
U^{A}\triangleq L^{T_{L}^{M,A}}\quad,\quad\quad V^{A}\triangleq M^{T_{L}^{M,A}}\quad.
\]
In a shorter notation, $U\triangleq L\circ T_{L}^{M}$ and $V\triangleq M\circ T_{L}^{M}$.
We have the \lstinline!swap! functions 
\begin{align*}
\text{sw}_{L,T} & :T_{L}^{M}\circ L\leadsto L\circ T_{L}^{M}\quad,\\
\text{sw}_{M,T} & :T_{L}^{M}\circ M\leadsto M\circ T_{L}^{M}\quad,
\end{align*}
defined using the already given methods \lstinline!flift! and \lstinline!blift!
of $T_{L}^{M}$ as
\begin{align*}
\text{sw}_{L,T} & =\text{blift}^{\uparrow T}\bef\text{ftn}_{T}\bef\text{pu}_{L}\quad,\\
\text{sw}_{M,T} & =\text{flift}^{\uparrow T}\bef\text{ftn}_{T}\bef\text{pu}_{M}\quad.
\end{align*}
We can define the monad methods $\text{ftn}_{U}$ and $\text{ftn}_{V}$
using these \lstinline!swap! functions. Will $U$ and/or $V$ be
lawful monad transformers for $L$? 

\subsubsection{Exercise \label{par:Exercise-1-interchange-laws-for-ftn-T}\ref{par:Exercise-1-interchange-laws-for-ftn-T}}

For any two monads $L$ and $M$ and a natural transformation \lstinline!swap!$\,:M\circ L\leadsto L\circ M$,
assume that the method $\text{ftn}_{T}$ of the monad $T=L\circ M$
is \emph{defined} via \lstinline!swap! by Eq.~(\ref{eq:define-flatten-via-swap}).
Show that the two interchange laws must then hold for $\text{ftn}_{T}$:
\begin{align*}
{\color{greenunder}\text{inner interchange law}:}\quad & \text{ftn}_{L}\bef\text{ftn}_{T}=\text{ftn}_{T}^{\uparrow L}\bef\text{ftn}_{L}\quad,\\
{\color{greenunder}\text{outer interchange law}:}\quad & \text{ftn}_{T}\bef\text{ftn}_{M}^{\uparrow L}=\text{ftn}_{M}^{\uparrow L\uparrow M\uparrow L}\bef\text{ftn}_{T}\quad.
\end{align*}


\subsubsection{Exercise \label{par:Exercise-2-prove-compat-laws-for-T-from-swap}\ref{par:Exercise-2-prove-compat-laws-for-T-from-swap}}

With the same assumptions as Exercise~\ref{par:Exercise-1-interchange-laws-for-ftn-T}
and additionally assuming the inner and outer identity laws for \lstinline!swap!
(see Statement~\ref{sec:Statement-swap-laws-to-monad-transformer-first-law}),
show that the monad $T\triangleq L\circ M$ satisfies two \textsf{``}pure
compatibility\textsf{''} laws:\index{pure compatibility laws@\texttt{pure} compatibility laws}
\begin{align*}
{\color{greenunder}\text{inner pure compatibility law}:}\quad & \text{ftn}_{L}=\text{pu}_{M}^{\uparrow L}\bef\text{ftn}_{T}\quad:L^{L^{M^{A}}}\rightarrow L^{M^{A}}\quad,\\
{\color{greenunder}\text{outer pure compatibility law}:}\quad & \text{ftn}_{M}^{\uparrow L}=\text{pu}_{L}^{\uparrow T}\bef\text{ftn}_{T}\quad:L^{M^{M^{A}}}\rightarrow L^{M^{A}}\quad,
\end{align*}
or, expressed equivalently through the \lstinline!flatMap! methods
instead of \lstinline!flatten!:
\begin{align*}
\text{flm}_{L}\big(f^{:A\rightarrow L^{M^{B}}}\big) & =\text{pu}_{M}^{\uparrow L}\bef\text{flm}_{T}(f)\quad,\\
\big(\text{flm}_{M}(f^{:A\rightarrow M^{B}})\big)^{\uparrow L} & =\text{pu}_{L}^{\uparrow T}\bef\text{flm}_{T}(f^{\uparrow L})\quad.
\end{align*}


\subsubsection{Exercise \label{subsec:Statement-search-and-selector-monads}\ref{subsec:Statement-search-and-selector-monads}}

Define a \textsf{``}search monad\textsf{''} by $\text{Search}^{P,A}\triangleq\left(A\rightarrow\bbnum 1+P\right)\rightarrow\bbnum 1+A$.
The function 
\begin{lstlisting}
def finder[A, P](s: (A => Option[P]) => A): (A => Option[P]) => Option[A] = {
  p: (A => Option[P]) => p(s(p)).map { _ => s(p) }
}
\end{lstlisting}
\[
\text{finder}:\text{Sel}^{\bbnum 1+P,A}\rightarrow\text{Search}^{P,A}\quad,\quad\quad\text{finder}\,(s^{:\text{Sel}^{\bbnum 1+P,A}})\triangleq p^{:A\rightarrow\bbnum 1+P}\rightarrow p(s(p))\triangleright\,\begin{array}{|c||cc|}
 & \bbnum 1 & A\\
\hline \bbnum 1 & \text{id} & \bbnum 0\\
P & \bbnum 0 & s(p)
\end{array}\quad,
\]
transforms a selector monad into a search monad. Show that \lstinline!finder!
is \emph{not} a monad morphism $\text{Sel}^{\bbnum 1+P,\bullet}\leadsto\text{Search}^{P,\bullet}$.

\subsubsection{Exercise \label{subsec:Exercise-selector-and-continuation-monads}\ref{subsec:Exercise-selector-and-continuation-monads}{*}}

Show that the following function $q:\text{Sel}^{P,\bullet}\leadsto\text{Cont}^{P,\bullet}$
is a monad morphism:
\begin{lstlisting}
def q[P, A](s: (A => P) => A): (A => P) => P = { f: (A => P) => f(s(f)) }
\end{lstlisting}
\[
q:\text{Sel}^{P,A}\rightarrow\text{Cont}^{P,A}\quad,\quad\quad q(s^{:(A\rightarrow P)\rightarrow A})\triangleq f^{:A\rightarrow P}\rightarrow f(s(f))\quad.
\]

Hint: Use the flipped Kleisli technique to simplify the proof of the
composition law.\index{flipped@\textsf{``}flipped Kleisli\textsf{''} technique}

\subsubsection{Exercise \label{subsec:Exercise-monad-product}\ref{subsec:Exercise-monad-product}}

\textbf{(a)} Show that the product of three monads $K^{\bullet}\times L^{\bullet}\times M^{\bullet}$
is again a monad.

\textbf{(b)} Show that the type isomorphism $(K^{\bullet}\times L^{\bullet})\times M^{\bullet}\cong K^{\bullet}\times(L^{\bullet}\times M^{\bullet})$
is also a \emph{monad} isomorphism.

\subsubsection{Exercise \label{par:Exercise-mt-3-1}\ref{par:Exercise-mt-3-1}}

The construction of the free pointed monad on $M$, namely $N^{A}\triangleq A+M^{A}$
(where $M$ is a given monad), uses a helper function $\gamma_{M}$
defined by
\[
\gamma_{M}:A+M^{A}\rightarrow M^{A}\quad,\quad\quad\gamma_{M}\triangleq\,\begin{array}{|c||c|}
 & M^{A}\\
\hline A & \text{pu}_{M}\\
M^{A} & \text{id}
\end{array}\quad.
\]
Show that $\gamma_{M}$ is a monad morphism between the monads $N$
and $M$.

\subsubsection{Exercise \label{par:Exercise-mt-3}\ref{par:Exercise-mt-3}}

For any monads $K$ and $M$ and a given monad morphism $\phi:K\leadsto M$,
show that one can implement a corresponding monad morphism $\psi:L\leadsto N$
between free pointed monads $L^{A}\triangleq A+K^{A}$ and $N^{A}\triangleq A+M{}^{A}$.

\subsubsection{Exercise \label{par:Exercise-mt-3-3}\ref{par:Exercise-mt-3-3}}

\textbf{(a)} Given two natural transformations $\phi:K^{A}\rightarrow M^{A}$
and $\chi:L^{A}\rightarrow M^{A}$, show that the function 
\[
\psi:K^{A}+L^{A}\rightarrow M^{A}\quad,\quad\quad\psi\triangleq\,\begin{array}{|c||c|}
 & M^{A}\\
\hline K^{A} & \phi\\
L^{A} & \chi
\end{array}\quad,
\]
 is also a natural transformation.

\textbf{(b)} Given a natural transformation $\psi:K^{A}+L^{A}\rightarrow M^{A}$,
show that the functions $\phi:K^{A}\rightarrow M^{A}$ and $\chi:L^{A}\rightarrow M^{A}$
defined by
\[
\phi\triangleq(k\rightarrow k+\bbnum 0)\bef\psi\quad,\quad\quad\chi\triangleq(l\rightarrow\bbnum 0+l)\bef\psi\quad,
\]
are both natural transformations.

\subsubsection{Exercise \label{par:Exercise-mt-3-2-1}\ref{par:Exercise-mt-3-2-1}}

For a given monad $K$, define $L$ as the free pointed monad $L^{A}\triangleq A+K^{A}$. 

\textbf{(a)} Show that the monad transformer $T_{L}^{M}$ for $L$
cannot be defined as the monad $P^{A}\triangleq A+T_{K}^{M,A}$ because
(at least for some monads $K$ and $M$) there is no monad morphism
$\text{flift}:M\leadsto P$.

\textbf{(b)} Given a runner $\theta_{K}:K\leadsto M$, where $M$
is an arbitrary (but fixed) target monad, implement a runner $\theta_{L}:L\leadsto M$
and show that $\theta_{L}$ is a monad morphism when $\theta_{K}$
is one.

\textbf{(c)} Show that it is \emph{not} possible to implement a monad
morphism $\theta_{K}:K\leadsto M$ given a monad morphism $\theta_{L}:L\leadsto M$,
at least for some monads $K$ and $M$.

\textbf{(d){*}} Given a monad morphism $\theta_{L}:L^{A}\rightarrow A$,
implement a lawful monad morphism $\theta_{K}:K^{A}\rightarrow A$. 

\subsubsection{Exercise \label{par:Exercise-mt-3-2}\ref{par:Exercise-mt-3-2}}

For a given monad $K$, define $L$ as the free pointed monad $L^{A}\triangleq A+K^{A}$.
Given a monad morphism $\phi:K\leadsto L$, implement a monad morphism
$\delta:K\leadsto\text{Opt}$.

\subsubsection{Exercise \label{par:Exercise-mt-3-2-2}\ref{par:Exercise-mt-3-2-2}}

It follows from Statement~\ref{subsec:Statement-monad-with-quantifier}
that adding a type quantifier to a monad gives again a monad. Show
that adding a type quantifier to any inductive typeclass (Section~\ref{subsec:Inductive-typeclasses})
gives again an inductive typeclass. In detail: assume an inductive
typeclass defined via a structure functor $P^{R,\bullet}$ that has
an extra type parameter $R$. All methods of the typeclass are then
contained in a value of type $P^{R,A}\rightarrow A$, where the type
$R$ is fixed. Show that $\forall R.\,P^{R,A}\rightarrow A$ is again
an inductive typeclass.

\subsubsection{Exercise \label{subsec:Exercise-effectful-list-not-monad}\ref{subsec:Exercise-effectful-list-not-monad}{*}}

Assume an arbitrary monad $M$ and define $L^{A}\triangleq\bbnum 1+A\times M^{L^{A}}$
as before.

\textbf{(a)} Show that any (fully parametric in $M$) implementation
of \lstinline!flatten! for $L$ (with type signature $\text{ftn}_{L}:L^{L^{A}}\rightarrow L^{A}$)
must truncate the nested effectful list whenever it encounters an
empty sub-list. To see the truncating behavior in a simpler way, take
$M=\text{Id}$, which reduces $L$ to the ordinary list ($L^{A}\triangleq\bbnum 1+A\times L^{A}$).
Show that the \lstinline!flatten! method for $L$ must evaluate to
a truncated list, e.g.:
\[
\text{ftn}_{L}(\left[\left[1,2\right],\left[3,4\right],\left[\right],\left[5,6,7,8\right]\right])=\left[1,2,3,4\right]\quad,
\]
instead of the full flattened list $\left[1,2,3,4,5,6,7,8\right]$. 

\textbf{(b)} Implement a non-standard \lstinline!List! monad whose
\lstinline!flatten! method has the truncating behavior demonstrated
in \textbf{(a)}, and prove that the monad laws still hold.\index{monads!List monad with truncation@\texttt{List} monad with truncation}

\textbf{(c)} Show that the functor $L$ \emph{cannot} serve as a monad
transformer for the (non-standard) \lstinline!List! monad defined
in \textbf{(b)}, because a lawful \lstinline!flift! function with
type $M^{A}\rightarrow L^{A}$ cannot be implemented.


\subsubsection{Exercise \label{par:Exercise-combined-codensity-monad}\ref{par:Exercise-combined-codensity-monad}{*}}

\textbf{(a)} The \textbf{composed} \index{codensity monad!composed}\textbf{codensity
monad} $\text{Cod}_{F}^{M,A}$ is defined by
\[
\text{Cod}_{F}^{M,A}\triangleq\forall X.\,(A\rightarrow F^{X})\rightarrow F^{M^{X}}\quad,
\]
where $M$ is a monad and $F$ is any functor. One may define the
monad instance for $\text{Cod}_{F}^{M,A}$ via the flipped Kleisli
composition:
\[
f^{:\forall X.\,(B\rightarrow F^{X})\rightarrow A\rightarrow F^{M^{X}}}\tilde{\diamond}g^{:\forall Y.\,(C\rightarrow F^{Y})\rightarrow B\rightarrow F^{M^{Y}}}\triangleq\forall Z.\,k^{:C\rightarrow F^{Z}}\rightarrow\big(k\triangleright g^{Z}\triangleright f^{M^{Z}}\big)\bef\text{ftn}_{M}^{\uparrow F}\quad.
\]
Prove that the type constructor $\text{Cod}_{F}^{M,\bullet}$ is a
lawful monad.

Hints: Use the flipped Kleisli formulation of the monad laws. Assume
that values of type $\text{Cod}_{F}^{M,A}$ are natural transformations
that satisfy an appropriate naturality law.

\textbf{(b)} Show that the quantifier $\forall X$ cannot be removed
from the definition of $\text{Cod}_{F}^{M,A}$ even if $F^{A}\triangleq A$:
show that for a fixed type $X$ and for some $M^{\bullet}$, the type
constructor $L^{A}\triangleq(A\rightarrow X)\rightarrow M^{X}$ is
\emph{not} a monad.

\subsubsection{Exercise \label{subsec:Exercise-pair-functor-is-rigid}\ref{subsec:Exercise-pair-functor-is-rigid}}

Rigid functors are defined in Section~\ref{subsec:Rigid-functors}.

\textbf{(a)} Show that the functor $F^{A}\triangleq A\times A\times A$
is rigid. 

\textbf{(b)} Show that the functor $F^{A}\triangleq\bbnum 1+A\times A$
is not rigid. 

\textbf{(c)} Show that the functor $F^{A}\triangleq\left(A\rightarrow Z\right)\rightarrow Z$
is not rigid ($Z$ is a fixed type).

\begin{comment}
Chapter eleven of the functional programming tutorial computations
in a central context have been one of the teams in this tutorial and
this is a final part this which talks about moon and transformers
to begin let me look at some code that needs to compute a value in
the future but the value is of optional type so these kind of computations
often happen in application code when you are computing some value
in the future but the value itself has additional logic and option
is a simplest such example so imagine that we would like to implement
a program that computes a value using a future and then if this value
is a non-empty option the computation continues and then it can compute
another value again in the future using what was concluded before
and that computation again returns an optional type and we again see
if that is a non-empty option and if so we continue and return another
future value and so on and if at any time this option is empty after
having computed it we need to stop some way short-cut the computation
by returning a feature of none right away so that\textsf{'}s what we have to
do so the code then starts looking like this now I just write here
option of one very simple computations for which I wouldn't have to
do such coding but in real life test as a function that takes time
to compute so I put it into a future and then it might return an empty
result I don't know that in advance let\textsf{'}s suppose and then I need
to match on that result so you see this code is quite difficult to
read and difficult to modify that is to maintain and the reason is
that it\textsf{'}s full of repetitions so there are all these match expressions
that always have the same structure if there is a Sun then we continue
if there is none then we were transfusion successful now it is precisely
that kind of repetition that was eliminated by using the function
block or the for yield block but so we eliminate them but only for
the outer type constructor the inner type constructor remains and
we still have to do the same thing for it and we could not use the
same for yield block to deal with the future chaining and the option
chain because this is a limitation of the function block the factor
in which we perform the computation must be the same throughout the
entire function block so the full yield delimit a block of thunder
computations where to the right-hand side of the arrow there must
be always the same factor type so future in this example once the
first line is giving you a future everything to the right of the arrow
must be of type future of something so it\textsf{'}s future this also must
be future which it is will have having the right code like this and
so on so it could not be that in the next line I write something like
X is equal to X X going to X hoped this would not actually compile
because this X optical type option it is not of type future of something
so this would not actually compile and that\textsf{'}s why we need to write
this code so this difficult to write and difficult to maintain code
unfortunately is unavoidable if we simply use the function block on
the type constructor that is nested when you have one monad and composed
in the type constructor with another monnet like this we will have
this problem whenever this happens so this could be a future of option
or it could be a list of either or any kind of combination like that
will give rise to ugly code of this kind so one solution that could
be easy to implement is to wrap this type constructor into a new class
for which we implement a monad syntax directly so here\textsf{'}s how it works
so we create a type wrapper which is just a case class with a single
value inside and this wrapped value is of type future option and now
we directly define for this case class the methods map and flatmap
and they're defined by simply doing a nested map and then and the
map inside so that\textsf{'}s nested flat map and then we write this code where
we match on the resulting option by hint so so this basically replaces
all the repetitive code above were in the case of none where we turn
a successful future of none and if the case of nonempty option then
we continue we continue with the next computation so that is the flat
map defined for this wrapped class once we have done this we also
do some convenience functions which I will talk about later such as
the lift and I define for convenience some implicit conversions so
that I can just convert future of a into this future option where
I promote a to option trivially by using some apply and another opposite
conversion converts the nested type constructor into a wrapped s to
type constructing automatically so that is what I do here once this
is defined the code above is magically transformed into this so the
pure computations are just examples like I said this is a very simple
example and don't really need to do this future option stuff in real
code this would be a function that returns a value of type future
of option of something and it could have been non-trivial could return
in the future that fails or it could return a future that succeeds
with an empty option or it could return a future with succeeds with
a non-empty option and so now the code becomes very straightforward
easy to maintain at the same time I could do operations like this
or else directly on this type where the or else refers to the optional
type inside future I implemented there or else for convenience like
this and the left is a function that transforms option a option B
into a future option A to future shouldn't be so this is kind of a
lifting of that kind so this is the basic idea of monad transformers
namely how to avoid having to write repetitive code languages and
instead write with some of course and definitions that you need to
do but eventually you would write code language so in other words
we could say we have combined a future monad and the option monad
into one big moment future with option which we can manipulate in
a functor block director with no need for pattern matching or anything
else so all the pattern matching within the future is done automatic
so this is an example of combining two monads so it is very often
necessary to combine different monad effects where effect is informal
notion it is not a specific clearly defined type it is an informal
notion which expresses the idea that in in a monad M the type of dysfunction
expresses a computation that takes a and computes perhaps a value
of B and also to compute something else or something else happens
while we were computing a value of B or maybe you compute many values
of B or maybe none at all or maybe you fail with some error message
or maybe something else happens so whatever else happens while you're
computing be from a in this function that\textsf{'}s the effect of the monad
M and so an example would be for option is that the computation can
have no result or a single result for list computation to have multiple
results for either it could fail to obtain the result and then report
an error for the reader it always gives a result but it needs to read
an external value for that writer it always gives a result but additionally
there is some accumulator which is of a monoid type and some value
will be appended to that accumulator for the future you might compute
computer value might fail with an error but all of that will be run
later it will not be computed right away so those are the effects
of some standard monads and often you would like to combine them so
you would like to have a list of either-or future of options and learning
and that could be given combinations of more than two when you want
to combine reader and writer and future at the same time so how do
we combine effects well I just showed you a code where I combined
effects although it required me to do acquainted quite some work obviously
what you could not do is you could you could not simply write code
with first a future of something which has a future type and then
a different monad on the right side of the arrow that would not compile
so if this has a type try and this has a type future they're not compatible
future and try are not compatible types and so this would not work
if you wanted to do that and you need to do something else you'd have
to unify both right-hand sides into a bigger moment such that you
somehow transform this into the value of a bigger monad he also transformed
this into the value of a bigger movement so these operations are called
lifting so you lift the small nut into the bigger moment you also
lift the small nut and a bigger more not and then if you can do that
and I have done this in my code I just showed you using an implicit
conversion so if I can do that I can just write code like this indeed
and implicit conversions will take care or maybe I can just put some
type annotations and in there that would take care of types and then
on the right hand side of the accumulator arrow I will always have
the same type constructor and that is therefore I'm going to be valid
Scala code so to see that this is not valid it\textsf{'}s easy to see that
because I should translate this into flat maps see the first thing
is in sequence the second thing is the future so the flat map on a
sequence takes this function but the future is a different kind type
constructor than the sequence on a flat map has a type signature that
requires a sequence here so that would not compile so the conclusion
is that in order to combine different effects in the same function
block we need to unify all these effects in a new unit that is in
some sense larger than all the previous monads and contains all of
them so the main goal of this chapter is to learn how we can compute
the type of this new moon at how can we decide what that type constructor
is how to implement the moon add instance for it for any kind of moon
does that you might want to use so there are several ways of combining
two models into a new bigger moon at that we could try and many of
these ways just won't work so the easiest way would be well why don't
I just take a product of these two moons that\textsf{'}s a monad we know that
the reason is that this is not what we need this is a moon Atias but
it describes two separate values of type a each having a separate
effect on it that\textsf{'}s not what we need we need a single value of type
a that has a combination of two effects possibly and that\textsf{'}s not all
this describes now maybe a disjunction because that could be the first
effect on a or the second effect on a unfortunately this is usually
not a monad and even even if it is a monad this is really a choice
between two different effects work even two different values it\textsf{'}s
not one value with the combination of two effects with with the first
effect and the second effect remember the Scala speech revulsion the
combination is at the same time being computed in the future and it
returns an optional result so this doesn't work now the next what
we can try is functor composition so we can pose and one of them -
we can compose in two different orders and sometimes indeed that works
it is often at one end when you compose so let\textsf{'}s look at some examples
but if one unit is this and the second model is this then we can compose
and the composition is this type constructor and that is actually
correct it as a monad similarly future of option as I just showed
can be combined in case a moment unfortunately if you try to combine
in there in the other order for example do some following this or
something like this those are not units so you can combine option
and reader this is the reader who not only in one order you can come
compose reader outside and options if you try option outside and you're
either inside the result is not imminent also you cannot combine State
mana with other moons like this so for example neither disorder nor
that order is a minute so from these examples we see first of all
sometimes it works but sometimes it requires a specific order of composition
and it does not work with the other order and sometimes it does not
work with composition at all so I will show that later that the state
monad is such that it does not compose with other monads in either
order so as a comment when composition works both ways and example
would be either and writer so they can be composed in both ways this
would be one result of composition this would be another and both
of these are monads but these moments express different kinds of effects
so for instance here we either compute result and write a message
or everything failed we have an error message will have no result
and no blog messages here we have always a log message the computation
may fail does not give us a result of type a but the log message is
always written so we can have an error message and a log message in
the same time so these are obviously two different kinds of logic
that you could express or two different kinds of effects so the task
in front of us is of course to avoid try on there we don't want to
do that every time that we need to compose two monads we need to have
a general way defining a new combined monads and we need to show that
it is always a moment so that we don't have to prove things every
time when we write code so that is what we would like to achieve and
we would go a very long way towards that goal in this chapter so what
we would achieve is that we will have a monad say Big M big manga
that somehow combines only effects so instead of the code that I showed
here which is invalid trying to combine the sequence future and try
in a single functor block that is not valid but if we somehow define
a big model that combines sequence future and try in the same big
moment then we had also we would have three functions for lifting
I would call them lifts one left two and lifts three for now which
would lift a sequence value into the big model a future value into
the big wallet and a try value into the big magnet so then we could
just write a function block like this lift lift lift after lifting
the right hand sides are of type big M of something this is now valid
and this would work the result would be of type maybe Big M of int
or something here are two examples of these liftings so combining
future and option would require us to define two liftings option a
into future option a and future in the future optionally so these
lifters are easy define and that\textsf{'}s how we would probably have to write
code in another example suppose we want to combine list of track list
and try so that works try inside the list networks I don't think that
try would work outside the list as I'm Oona and these are the two
lifting so that\textsf{'}s easy enough and you see that could work now they're
still of course a lot of work to be done if we were to go this way
for each pair of moments or even for each combination which could
be very very many we would have to define these wave teams we'd have
to define the monad instance for a big M I haven't even talked about
that I haven't even said what the type of Big M is for this combination
for this I know but for this I haven't said that so how to combine
list feature and try in a single type constructor this is a non-trivial
question which is not easy to resolve by trial and error composition
would not necessarily work we need also to check that the laws of
the mana told for these moments which I also will check but haven't
done yet so all these questions remain is it always possible how to
find such a type constructor is it unique are there several options
alternative solutions are they some of them better than others these
liftings what are the laws that they have to satisfy and and so on
also can we somehow reduce the complexity instead of having to define
liftings for all possible combinations maybe we find fewer and make
other things automatic so let me first talk about the laws of liftings
so we assume that there will be a monadic program such as this one
with some liftings and we ask what are the laws for these liftings
now we assume that the monads m1 m2 and also the big model whatever
it might be already satisfied all the Monad laws how would we argue
about lifting laws so for example imagine a functor block in which
we have code like this so first we have a lifting of a pure value
so we have an m1 pure and we lift it so that becomes a big moon add
value and then we continue with some big monad stuff depends on high
now since this is just pure our initial code without liftings which
is incorrect would have been just I going to the pure of X and then
continuing with that I usually code like this is equivalent to this
kind of code where we don't need to do monadic arrow and the left
arrow we don't need that if we just use pure we just say i equals
x and continue and so we expect that with lifting it will be the same
that we can replace this code with this equivalently so this is a
law that the function lift must satisfy we write it down is like this
this is the law now of course it\textsf{'}s not very nice to reason about code
so I prefer to reason about a more condensed notation rather than
Scala code syntax and in particular it is convenient often to use
the closely composition criminals which is composition of functions
of these types the nicely functions and so if we rewrite this code
in terms of closely functions then it looks like this the composition
of the flow-rate composition of pure of n1 and lifts one flat map
with some arbitrary B which is some x2 big animals voice this is this
B must be equal to B so that\textsf{'}s what we get if we remember that the
classic composition is replacing this kind of code so F composition
with G is a function that is like this another law is that if we have
a lifting of pure after some valid computation then we expect that
this X again has just ik equal to Omega there\textsf{'}s no effect here and
this should remain so after lifting so therefore this code must be
equivalent to this code writing the same code that is the equation
like this and writing it in terms of the class like composition it
becomes this equation and of course the same identity laws must hold
for the second moment in its second lifting so these moments we consider
to be only cause fruiting right now and both of them need to be lifted
into the big mullet if this construction is to be of practical use
now these laws are kind of complicated let\textsf{'}s simplify them these laws
basically say that this function this this composition of pure em
and lift is the identity for the closely composition so this Purim
lifts to the left of B equals B and p.m. lift to the right of B also
equals B and so this function is the unit for the classic composition
but this monad already has a unit in the classical composition laneway
it as this viewer of the Big M and in the Monod the two-sided unit
element is unique and similarly this is so in a closely composition
so if you have two different unit elements U and u Prime and we can
easily write this equation which is that you Kleist a product u prime
it must be equal to u because U prime is a unit element it also must
be equal to u prime because u is the unit element and so u must be
equal to u prime so the unit element is always unique and so these
two identity laws that we have seen here can we actually produced
a single or equivalent to saying that this forward composition of
pure hand and lift it must be equal to the pure function of the big
moment so we have now reduced the identity law to a single identity
law and let us now derive another one for the lifting which is that
if we have some kind of lift one of everything so we have a portion
of a program that just uses the first moment and keeps lifting it
into the big moment we should be able to refactor this into a nomadic
program that only works within the first moment and then lift the
result of that program into the big moment so this would be the equivalent
program first we'll do the flat map in the moon atom one and then
we lift the result into the big moment so this program it is kind
of reasonable should be equivalent to this if it\textsf{'}s not it would be
kind of strange that I cannot refactor my programs the idea is that
lifting should be transparent it should be just tight from massaging
for the moment so usually if I have a nomadic program like this imagine
there\textsf{'}s no lifting I can always refactor it I can do this what not
somewhere else and then put the results of that flat map back here
you can always do that that\textsf{'}s the usual associative 'ti buna so I
should be able to do the same if I lift into the big moment so that
law when written out it becomes this equation and unfortunately now
this is a little unwieldy to you to think about so let let us rewrite
it equivalently through the flat map function so the flat map function
which I did denote F L M it is with this type signature which is not
the same as the usual flat map in scala but it is easier to reason
about and then using this flat map we write this code like that so
we have a lift then we have a flat map of this function and then it\textsf{'}s
the same as first doing a flat map and then lifting the result on
both sides of this law are functions of this type signature lifting
and one into the big moment we can further simplify this if we rewrite
flat map through flatten flatten has this type signature and the law
becomes lift one and then lift one lifted four raised to the big moment
using its map function and then followed by flat map in the big Monat
is equal to flat map in the m1 mu not followed by lift so these are
easy to obtain if you remember that flat map is map followed by flatten
in other words it\textsf{'}s this map followed by flat so that\textsf{'}s basically
how I get from here to here and the function Q disappears from the
law in this formulation so it becomes simpler there\textsf{'}s no arbitrary
function from A to B nothing like that it\textsf{'}s just both sides are functions
of this type there\textsf{'}s only one type a involved as a type parameter
whereas in this law there is a function q and they're two type parameters
a B and in this formulation they're two arbitrary functions P and
Q so in this way the laws is simply the law is simplified can be simplified
even more if we write it in terms of Chrysler composition then it
becomes a law that is for some functions B and C of class Li type
signature the be lifted and closely composed with C lifted is equal
to twice Li composition of B and C all lifted notice I am using two
different closely compositions in this law and the left I am using
the class decomposition in the big moon on the right in the moon at
M one to make it clear I use the subscript in each case so this is
maybe slightly more difficult to read with the subscript so squint
at it and imagine that the subscript isn't there keep it just in mind
and then you see be lifted composed with C lifted is be composed C
all lifted so that\textsf{'}s the composition law in other words the lifting
of functions before composition is equal to lifting of functions after
composition in other words the liftings commute with a closely competition
and also the lifting is commute with pure pure after lifting is the
same as the other pure and so the laws expressed the idea intuitively
that these liftings lift 1 and lift two of course as well should commute
with the operations pure and flatmap of the magnets so this is how
we can think about these laws and remember them so the liftings must
lift peer-to-peer and compress a closely composition into classically
composition additionally the liftings must be natural transformations
but actually it is a consequence of the fact that they lift pure to
pure and flatmap to flat map or flattened to flatten or glass the
composition to place the composition now the term that I use for such
functions and that commute with monads and lift purity pure and flat
map to flatten ax is monad morphism so it\textsf{'}s not just the function
or morphism but it\textsf{'}s a monad morphism in other words it\textsf{'}s a morphism
that agrees or is compatible with the structure of the moon and and
it\textsf{'}s a function between f1 and Big M so it is compatible in this way
with structures of these two moments whatever structure is an n1 it
maps into that corresponding structure in Big M and in the previous
chapter we already saw an example of an antique morphism although
we did not talk about it I didn't talk about it I talked about magnetic
interpreters not run one one addict program and obtain a monadic value
in another moment these must actually satisfy these laws in order
to be useful and so Mahna Mahna the interpreters are always magnetic
morphisms unless they are be very useful and now let me derive the
naturality law for this lift now lift has this type signature so naturality
for it means that if i have some function f from X to Y and I lifted
to m1 and I also lifted too big him so that\textsf{'}s the F map of 1/2 and
I am in m1 or in Big M then the lifting must commute with that so
in other words first you lift and then you map X to Y or you first
map X to Y then you lift it doesn't matter and that is the equation
that we can write expressing this equivalent system now we can derive
this law actually from the fact that lift is a magnetic morphism so
this is not a separate law that we need to check once we know that
it is a one-man ignore thism how so this is a derivation F map can
be expressed through a flat map and pyrrha and that is a monad law
for both movements and then this is the lifting law for flat map and
instead of saying this so we write that so this column of F here is
the left hand side or actually that the right hand side of this law
is f map f lift 1 so instead of f map I write this and the result
is that so in this way I what I'm trying to get is that I replace
in this law F Maps through F Elam and the right and on the left and
I hope that I get an identity after that so I begin with the left
hand with the right hand side where I replaced F map through a felon
now I used this law that FLM of some function and then lifted is lifting
followed by a column of this where Q is equal to a composition of
F and P rm1 so that results in this expression we have left one FLN
Big M which I didn't enjoy it of composition of this Q which is this
and left so that is here now I'll use the fact that pure M followed
by lift one is pure Big M which is this law therefore I have here
F followed by pure Big M now this is flat map in Big M therefore this
is a law of Big M which is this okay which I can replace this by flat
by F map of begin so now the result is this which is the left hand
side of the law and trying to prove so I started from the right-hand
side replaced things in it identically and I got the left hand side
using the fact that lift 1 satisfies the laws of a magnetic north
ISM so monad morphism therefore is always a natural transformation
so how do we deal with the problem of combining many moments and reducing
the amount of work so to look at an example if we can bind listen
this on that only this combination works this is a functor composition
of this and this where the reader is outside and the option is inside
the other order would not work this is not a minute and so this destroys
our hopes of somehow always writing a formula combining M 1 and M
2 for arbitrary M 1 and M 2 using some kind of natural combination
or by functor this would not work and another example is that the
state monad does not compose in any order with other moons let me
show some code that explains why not a stone if I try to compose optional
is reader in the other order then I try to combo I'd really defined
flatmap further also and define a flat map with this type signature
so I get so this o R is an option of reader and I need to get an or
R of B from or of a and the function a to or me now if FA is none
we have nothing to do except return there\textsf{'}s no a available in our
so they cannot possibly use F and return some non-trivial for B so
we have to return none here now suppose we have a non empty option
and then we have a function R T so now how can we return an option
of artemiy we have a function that takes a and returns this or B now
unfortunately we cannot use this F either because to use F we need
a function we need the value of that a but we don't have it we have
a function from R to a we don't have an R and so we cannot apply F
to anything at this point we have to decide at this point without
applying F which will give us some option we need to return either
a nun or a some heartily so trying to return the nun here would be
bad because then I would return none in both cases so we basically
have a flat model that always returns an empty option and that has
no hope of satisfying the identity law which is that flat map of something
with pure is equal to that something but if our flat map always returns
an empty option this will never work so let\textsf{'}s try to return a non
empty option okay so we start returning it we have an R now we can
use this function f by computing R to a of origin of type a and applying
F to that so we get an option over hard to be here but we are inside
this function we are required to return a value of type B but we don't
have that we have an option of something which could be none and this
point could be empty and if it is not empty as we can return the value
of time but if it is empty we are stuck we cannot return a value of
type B so there is no good implementation of flat map in this case
a pure we can implement with a flat map no let\textsf{'}s look at the statement
so this is the statement type constructor so let\textsf{'}s compose it with
reader well I need to implement flat map with this type signature
work as R is this combination the state with this radio inside now
I will follow the types and there\textsf{'}s only one way of implementing it
so we start with a function s we need to return as RB which is s going
to a pair of s and R to me so start with s then we can compute FA
of s we get these things now we want to return the pair of s 1 and
a function are to be now how do we get a be only way to get a B is
to apply the function f to some a so we have an a yes we can apply
after a we can give an R 2 that give it a B so finally we get a B
but we have to discard this value s not we obtained lust so and this
is suspicious in the state monad we should not discard updated values
of the state yes but we have to discard it because we are returning
must return s here and the function are to be is inside so we cannot
give this s which we only computed here back over and over there and
this is indeed the problem that we described certain parts of the
state so essentially we have not used f in computing the new state
I have used f to compute the new value but F only gives you not only
gives you a value it only gives you an effect of taking on the state
and is updating we are ignoring and indeed it will violate the identity
law which is this one of the identity laws and I can show that this
is so because if I compute the flatmap according to the code over
there then it will be a function that always ignores the value which
is okay it\textsf{'}s the pure but it always returns the unmodified state s
so the first element of the pair is always going to be unmodified
state s and this could not be equal to F it should it should equal
F this should equal f of X but it cannot because F could modify the
state language F could be of this form which modifies the state but
our flat map will never modify the state in this combination with
pure and so that cannot possibly be equal to f of X for arbitrary
functions F no F I could have an effect and we should have accumulated
that effect we are not now trying to compose state monad with reader
inside fails what about composing it outside let\textsf{'}s take an option
another simple model and compose it outside with state Bible you know
go through this in detail but it\textsf{'}s a very simple computation and basically
either you're always return none in your flattener an empty option
which is bad or you're stuck you're trying to return the value you
need and you don't get it you have an option of something but you
need that value itself so you have an option in the wrong place and
you're stuck you're not able to compute a be just like we're not able
to compute early previously so this shows that the state moment fails
to compose with other moments in either order so it does come to us
with some owners in one order in with other models in another order
but you cannot in advance say I compose the state monad outside with
an arbitrary other monad and that result is valid or not no that doesn't
work or inside no doesn't work so this is a problem and {[}Music{]}
the solution is actually what is called mono transformers the main
trick is that we're not going to try to combine arbitrary to monads
we're going to fix one moment which will go call the base model and
look I will denote it as L and for a fixed L I will let the other
one at vary so that will be called a foreign minute and we'll try
to assimilate the foreign minute into a fixed base model and combine
them in this way so the result is a type constructor on which I call
T LOM and it still has a type parameter you're not it here by this
placeholder symbol so this placeholder symbol is just a type parameter
that I'm not writing so I introduce this notation in the previous
chapter and this color this is written simply like that it says type
parameter that we're not writing so this type constructor depends
on both L and M and it gives you a new moment and it is such that
for a fixed L this M is actually a type parameter so this works for
a fixed L and for any M so fixed base model and arbitrary foreign
moment so that\textsf{'}s what that transformer is it\textsf{'}s a type constructor
it depends on L and M but it depends on them in a different way so
it is generic and M but not an L in other words for each L for each
baseman on L there is a different construction t om but the construction
is the same for all M so the fixed L the construction is the same
for all M so in other words its generic in him so right away that
is important to understand that there\textsf{'}s no general formula that takes
a monad L and produces the transformer doesn't seem to exist so for
each L for each base moment he'll we need a different construction
of the city em the foreign moment will be generic but the basement
will not be just a parameter and finally there is a question whether
some monads have a transformer or not now I don't know how to answer
this question but I do have examples of monads that don't have full-featured
transformers and maybe this is not a problem but I do not have examples
of monads where I don't know how to make a transformer so this question
seems to be difficult and in practice every moment that we can write
down as a type constructor will have a transformer or at least halfway
I will talk about this in more detail very soon so what is the advantage
of having this approach of using this approach when we fix the base
model and vary the foreign model the advantage is that now we can
easily compose three or more units by simply composing the Transformers
since the transformer is generic in this one on M I can put that monad
M as the type parameter and I can set it to a transformer for a different
moment I'm missing here another type parameter placeholder but the
notation is difficult as it is so in Scala for example you would have
transformers such as State T of list T of freighter so you can do
that with these placeholders which correspond to my lowitz and in
this way you can stack together many many wonders with no additional
work once you have implemented transformer for each Manette you can
stack any number of them like this so no need to have a combinatorial
explosion in how many different transformers you need combined future
and option future in list list an option listen either future and
either know it just implement a transformer for list transformer for
either transform an option transformer for reader and then you just
stack them and this is called the moon a stack but make sure you don't
mix together and one on stack and composition of type constructors
will functor composition because this is not the same as a simple
composition like this the transformer is not just a composition for
someone as it is but for others it is not unlike for the state model
it is not a composition as we have seen i cannot work as a composition
also for some units the composition goes inside and for others outside
the transformer is a type constructor that is always outside but the
result of it could be that some things are inside work or even transcribed
in some difficult way that is neither composition inside nor outside
so monad stack is not the same as composing type constructors formulas
this is not a minute this would not work well that transformers will
always work they will always produce and will not satisfy all the
laws so what are the requirements for mana transformers for all foreign
there must be the following properties so first of all this must be
a monad which I call the moon at em transformed with this transform
ITL so it\textsf{'}s a foreign moment that has been assimilated somehow onto
the base model and the result is this big larger moment that has both
effects there must be a lifting which is this function monad morphism
between em the foreign Monat and the transformer there\textsf{'}s also the
base lifting which lifts the basement in the new transformer but it
is not natural in L because L is not a natural type Brown or not generic
type parameter in the transformer another property is that if we take
the identity monad as M and the result must be equivalent to hell
and this is not natural because the identity monad does not have an
effect so if we transform that assimilate and that then just the effects
of L remain and that\textsf{'}s the same as just having L now the fact that
the transformer is magnetically natural in the mannered M means that
there are these other properties namely T must be paralyzed by him
as a type parameter and for any other moment in we could we should
be able to map M - n inside the T so if we know how to map M - n using
some melodic morphism then we should also know how to map transform
the M to transformed him so this I call em Ron so if I know how to
run the moon and em into some other moment and I should know how to
run the transform model into the transform the other monitor also
these runners must commute with lifts and baseless so if I first lift
and then run for example for lift L and then I run {[}Music{]} then
I should obtain the same result as when I first run and then lift
so we will look at the precise formulation of this a little later
now this naturality will always hold automatically as long as we implement
this mu not only using the moon had methods of him we don't use the
structure of M but only call its methods pure and flat map and this
situation is similar to what happened in chapter 9 when we talked
about I talked about Traverse so this Traverse had this type signature
and it was natural with respect to negative function f so did not
use the structure of the function f only the fact that it was a negative
and this therefore can be used to run the monad for example take this
runner if it exists and lift it to this runner which is a runner from
TM to L so we can eliminate the effects of M or run them evaluate
them perform them and get just an L which are so effects of L and
M were combined in this monad we can separately run or evaluate effects
of M and the effects of L should remain similarly there should be
a base runner where we can run the effects of L inside the transferrin
monad and the result is just M left that\textsf{'}s the base runner and again
it should commute with lift and base lifts why do we need these runners
well the only way to evaluate Mona\textsf{'}s is to run them to actually perform
the effects and unless these laws hold performing the effects would
give incorrect results when we combine the effects so we should be
able to combine the effects without changing our ability to run them
separately so we can combine L and M effects but we can run ill and
not M work we can just run em but not l separately as much as we can
as much as we need to separate them so these are the requirements
and I will go through these requirements later to prove that they
hold for all the monad transformers here are some first examples if
we have a reader then the reader composed outside works if we have
this mu knot which is a combination of either and writer then this
can be composed inside these are monarch instructions that I have
proved in Chapter 7 and actually these are ma not transformers for
these moments from the reader and for this moment which is a combination
of either and writer so therefore these are the Transformers reader
te 30 and writer T which we can write down immediately already having
proved that these are models we still haven't proved other laws but
we have proved that the Campbell combine types Ramona\textsf{'}s notice that
the reader composes with the foreign loan add from the outside but
either in writer compose inside that foreign unit and this must be
so other the other way around is wrong it doesn't work does not produce
a minute for her betray him which I just showed you thank God the
remaining questions for us so what about other movements so now we
chanced to know this before but what about other moments we don't
know and they don't compose me neither of them composes inside or
outside with arbitrary other monads so we also have a lot of other
melodic instructions how to find transformers for the results of those
constructions if we use them and if we know transformers for some
previous moment we made new moments out of previous moments how to
find transformers for them what about monads constructed using a transformer
what\textsf{'}s a transformer for that and whether it\textsf{'}s always possible as
like I said it is unknown maybe there are some owners that don't have
transformers I haven't seen good examples of that now is a transformer
unique now it is not almost sure why but usually there is one transformer
against preferred that\textsf{'}s the simplest and that\textsf{'}s what people usually
mean when they say the mono transformer and another final issue is
all this boilerplate around lift now lifting is still quite cumbersome
you need all this lifting and the code is cumbersome because they're
all these especially if you have more than two monads combined and
there\textsf{'}s lift of lift of lift in different orders and that makes code
difficult to maintain so there are solutions for that which are called
MTL style transformers until stands for monad transformer library
so I'll talk about these issues in order in the rest of this chapter
here\textsf{'}s an overview of all what I know about one on transformers each
one that has a different transformer so it\textsf{'}s really a zoology and
each construction is ad-hoc so there\textsf{'}s no general method for them
so some will not have composed inside transformer so these are the
option right here and either for each Monett we need to know what
that is so we will see how that works so for someone as it\textsf{'}s composed
inside for others it\textsf{'}s composed outside so this is the formula what
are those moments that can pose outside the reader and also there\textsf{'}s
a unit called the search monad which is this type which I have shown
before the chapter 7 I didn't call it specifically a search moment
but this and similar moments have transformers and that can pose outside
and more generally I define I will define a class of factors that
are called the rigid and muninn saturated or have outside transformers
so they're kind of they're they're generalizing the reader and this
kind of monad there are several other such types another type of monads
is recursive lists non-empty lists and free movement they are defined
recursively and neither of the compositions worked for them they need
a different construction which is interleaving the basement and the
foreign unit inside the recursion so it cannot be just composition
another type of monads is monads obtained from constructions so for
example product a unit has a product of transformers so you need to
know the transformer for L one transformer for L 2 and then you make
a product that is the transformer for the product monent another construction
that I already described in chapter 7 is this we have a contra factor
H and have a function from its to a so this construction works for
any control factor H and gives you a moment and this moment has a
composed outside transformer it is rigid another class of one else
is free pointed minutes this is also construction from chapter 7 a
transformer for that Monod looks like this it\textsf{'}s neither composition
outside nor inside and requires you to know the transformer for the
m'lad l and then you know how to define a transformer for this moment
finally there are irregular moments where none of these constructions
work for example the statement for the statement composition doesn't
work these constructions doesn't don't work you need to put the formula
at the precise spot inside the statement and then it works for the
continuation or not you need to put the foreign wallet in here otherwise
nothing works there is a another class of Mona\textsf{'}s that I call selectors
for them you have to do this again it\textsf{'}s neither composition nor constructions
like that finally there is a good density monitor which again you
have to put the foreign model inside at specific places so these are
irregular so each has its own recipe and there doesn't seem to be
much of a system here it is not clear that one odds could exist with
no transformers but one suspicious fact is that some transformers
do not have several of the required methods so for example the continuation
monad transformer does not have a base lifting in other words you
cannot lift a value of the continuation monad into the value of these
types of continuation when it is a - R - R cannot lift that into a
TOA Mart anymore for arbitrary yeah now this is a problem in my view
it means that these transformers are not fully usable they kind of
half work but unless I can lift both my monads into a transformer
I cannot really replace in the functor block the previous monad with
the big moment so in my view this is a problem and you could argue
that these transformers are incorrect they are not fully featured
they do not satisfy the required laws I couldn't get that and I will
talk about this later so now I begin with the composed inside transformers
which is the first class of transformers in my 
\end{comment}

\begin{comment}
\end{comment}

\begin{comment}
\end{comment}

\begin{comment}
\end{comment}

